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 "foo", "app"; returns true we can map f -> a and o->p
given "bar", "foo"; returns false we can‘t map both ‘a‘ and ‘r‘ to ‘o‘
given "ab", "ca"; returns true we can map ‘a‘ -> ‘b‘ and ‘c‘ -> ‘a‘
Solution 1: map
class Solution { public: bool isIsomorphic(string s, string t) { if(s.size()!=t.size())return false; map<char, char> m; for(int i=0;i<s.size();i++){ if(!m.count(s[i])){ map<char,char>::const_iterator iter=m.begin(); while(iter!=m.end()){ if(iter->second==t[i])return false; iter++; } m.insert(make_pair(s[i], t[i])); }else{ if(m[s[i]]!=t[i])return false; } } return true; } };
Solution 2:
bool isIsomorphic(string s, string t) {
if(s.size()!=t.size()) return false;
map<char,char> map1;
map<char,char> map2;
for(int i=0;i<s.length();i++){
char c1=s[i];
char c2=t[i];
if(map1.count(c1)){
if(map1[c1]!=c2) return false;
}
if(map2.count(c2)){
if(map2[c2]!=c1) return false;
}
map1.insert(c1, c2);
map2.insert(c2, c1);
}
return true;
}