题目:
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.
思路:使用map,两个字符串互相可转化
class Solution {
public:
/**
* @param s a string
* @param t a string
* @return true if the characters in s
* can be replaced to get t or false
*/
bool isIsomorphic(string& s, string& t) {
// Write your code here
if (s.length() != t.length()) return false;
map<char, char> Amap, Bmap;
map<char, char>::iterator Iter;
for (int i = 0; i < s.length(); i++) { // s->t
Iter = Amap.find(s[i]);
if (Iter != Amap.end()) {
if (Amap[s[i]] != t[i]) return false;
} else {
Amap[s[i]] = t[i];
}
}
for (int i = 0; i < s.length(); i++) { // t->s
Iter = Bmap.find(t[i]);
if (Iter != Bmap.end()) {
if (Bmap[t[i]] != s[i]) return false;
} else {
Bmap[t[i]] = s[i];
}
}
return true;
}
};