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.
Analyse:
1. map twice.
Runtime: 68ms.
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 class Solution { 2 public: 3 bool isIsomorphic(string s, string t) { 4 if(s.length() == 0) return true; 5 6 map<char, char> m; 7 map<char, char> n; 8 for(int i = 0; i < s.length(); i++){ 9 if(m.find(s[i]) == m.end() && n.find(t[i]) == n.end()){ 10 m[s[i]] = t[i]; 11 n[t[i]] = s[i]; 12 } 13 else 14 if(m[s[i]] != t[i] || n[t[i]] != s[i]) return false; 15 } 16 return true; 17 } 18 };
Runtime: 104ms.
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 class Solution { 2 public: 3 bool isIsomorphic(string s, string t) { 4 if(s.length() == 0) return true; 5 6 map<char, char> m; 7 m[s[0]] = t[0]; 8 for(int i = 1; i < s.length(); i++){ 9 if(m.find(s[i]) != m.end() && m.find(s[i])->second != t[i]) return false; 10 else 11 m.insert(pair<char, char> (s[i], t[i])); 12 } 13 map<char, char> n; 14 n[t[0]] = s[0]; 15 for(int i = 1; i < s.length(); i++){ 16 if(n.find(t[i]) != n.end() && n.find(t[i])->second != s[i]) return false; 17 else 18 n.insert(pair<char, char> (t[i], s[i])); 19 } 20 return true; 21 } 22 };
Runtime: 140ms
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 class Solution { 2 public: 3 bool isIsomorphic(string s, string t) { 4 if(s.length() == 0) return true; 5 6 map<char, char> m; 7 m[s[0]] = t[0]; 8 map<char, char> n; 9 n[t[0]] = s[0]; 10 for(int i = 1; i < s.length(); i++){ 11 if(m.find(s[i]) != m.end() && m.find(s[i])->second != t[i] || 12 n.find(t[i]) != n.end() && n.find(t[i])->second != s[i]) return false; 13 else{ 14 m.insert(pair<char, char> (s[i], t[i])); 15 n.insert(pair<char, char> (t[i], s[i])); 16 } 17 } 18 return true; 19 } 20 };