解法一,使用map,时间复杂度O(nlgn)。
class Solution { public: bool isIsomorphic(string s, string t) { /* if(s.length() != t.length()) return false; map<char, char> mp1; map<char, char> mp2; for(int i=0; i<s.length(); ++i){ auto it1 = mp1.insert(make_pair(s[i], t[i])); if(!it1.second){ if(it1.first->second != t[i]) return false; } auto it2 = mp2.insert(make_pair(t[i], s[i])); if(!it2.second){ if(it2.first->second != s[i]) return false; } } return true;*/ };解法二:使用unordered_map,时间复杂度O(n):
class Solution { public: bool isIsomorphic(string s, string t) { if(s.length() != t.length()) return false; unordered_map<char, char> umap1; unordered_map<char, char> umap2; for(int i=0; i<s.length(); ++i){ auto it1 = umap1.insert(make_pair(s[i], t[i])); if(!it1.second){ if(it1.first->second != t[i]) return false; } auto it2 = umap2.insert(make_pair(t[i], s[i])); if(!it2.second){ if(it2.first->second != s[i]) return false; } } };别人的解法:),也是O(n):
class Solution { public: bool isIsomorphic(string s, string t) { int m1[256] = {0}, m2[256] = {0}; for(int i=0; i<s.length(); ++i) { if(m1[s[i]] != m2[t[i]]) return false; m1[s[i]] = i + 1; m2[t[i]] = i + 1; } return true; } };