leetcode 205. Isomorphic Strings | str中字母计数(dict)与定位

来源:互联网 发布:西安理工大学知行 编辑:程序博客网 时间:2024/05/17 08:50

Description

Given two strings s and t, determine if they are isomorphic.

Two strings are isomorphic if the characters in s can be replaced to get t.

All occurrences of a character must be replaced with another character while preserving the order of characters. No two characters may map to the same character but a character may map to itself.

For example,
Given “egg”, “add”, return true.

Given “foo”, “bar”, return false.

Given “paper”, “title”, return true.

My solution

没有实践代码, 只有基本思路如下.
某些值相同, 则把索引放在同一个list里面. 两个str都做此处理, 按顺序对比dict的令一部分是否相同即可. 实现起来, 明显感觉有很大优化空间.

Discuss

class Solution {public:    bool isIsomorphic(string s, string t) {        int m1[256] = {0}, m2[256] = {0}, n = s.size();        for (int i = 0; i < n; ++i) {            if (m1[s[i]] != m2[t[i]]) return false;            m1[s[i]] = i + 1;            m2[t[i]] = i + 1;        }        return true;    }};

看懂了基本思路, 自己写如下:

class Solution {public:    bool isIsomorphic(string s, string t) {        if(s.size()!=t.size()) return false;        int a[256] = {0};        int b[256] = {0};        int cnts=0,cntt=0;        for(int i=0;i<s.size();i++){            if(a[s[i]]!=b[t[i]]) return false;            a[s[i]]+=1;            b[t[i]]+=1;        }        return true;    }};

看起来基本一样的代码, 我的是错误的. 差别在于我用的”+=1” ,参考代码是”=i+1”.
实际上, 这两种写法是实现了两个事情
- “+=1” 类似于python dict, 对txt中单词统计 d[‘word’]+=1的思路, 本问题中结果是统计了单词出现频率. 对于”aba”和”baa”这个测试用例不能通过.
- “=i+1” 给定值, +1也好+n也行, 作用就是记录这个元素最后出现的位置索引.不用”=i”的原因是最开始初始化为0, 如果是初始化了非0值, 也可以”=i”形式. 所以这个方法的关键思想就是, 在考察第i个元素的时候, 观察一下最后一次s和t中, 这个元素出现的位置是不是一致!! 思路略绕, 但很巧妙.

值得说明的是, 采用最大256长度的数组, 实现了类似于dict(c++ map)的单词统计的思路, 也是很有启发的.

Reference

  • leetcode 205
原创粉丝点击