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: one 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: two map
class Solution { public: bool isIsomorphic(string s, string t) { if(s.size()!=t.size()) return false; map<char,char> ms, mt; for(int i=0;i<s.size();i++) { char c1=s[i], c2=t[i]; if(ms.count(c1)) if(ms[c1]!=c2)return false; if(mt.count(c2)) if(mt[c2]!=c1)return false; ms.insert(make_pair(c1, c2)); mt.insert(make_pair(c2, c1)); } return true; } };