205. Isomorphic Strings
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.
S: hash map O(n)
注意双向的关系,也可用256长度的数组代替hash map
bool isIsomorphic(string s, string t) {
if (s.size() != t.size()) return false;
unordered_map<char, char> sTot;
unordered_set<char> tUsed;
for (int i = 0; i < s.size(); ++i) {
if (sTot.find(s[i]) == sTot.end()) {
if (tUsed.find(t[i]) == tUsed.end()) {
sTot[s[i]] = t[i];
tUsed.insert(t[i]);
} else {
return false;
}
} else if (sTot[s[i]] != t[i]) {
return false;
}
}
return true;
}