本题题目要求如下:
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.
Note:
You may assume both s and t have the same length.
说下大概的思路吧:
- 设一个hashmap,s[i]是key,t[i]是value,比如egg,第一个e对应a,然后g对应d,遇到第三个g的时候要检测,看看t[i]是不是等于hashmap[s[i]]的value,如果等于,即为d,则通过,如果不是,则直接返回true
- 上面的那个hashmap只保证了s里面的同样元素指向t的时候,也是相等的,但是不能保证不会出线s里面有两个不同元素的value都是一样的,比如hashmap[a] = a, hashmap[b] = a,要避免这种情况。。则,再新建一个hashset,这个hashset的key就是hashmap的value。若hashmap的key的数量和value的数量(hashset的大小)相等,说明这两个string是isomorphic
然后上传完整代码:
class Solution {
public:
bool isIsomorphic(string s, string t) {
int sz = s.length();
for (int i = 0; i < sz; ++i) {
auto pos = hashtable.find(s[i]);
if (pos == hashtable.end()) {
hashtable.insert({s[i], t[i]});
}
else {
if (hashtable[s[i]] != t[i])
return false;
}
}
/* final check */
for (auto it = hashtable.begin(); it != hashtable.end(); ++it) {
hashset.insert(it->second);
}
if (hashset.size() == hashtable.size())
return true;
else
return false;
}
private:
unordered_map<char, char> hashtable;
unordered_set<char> hashset;
};