Problem Description:
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.
我的方法是利用额外的空间来记录前面的map,每次遇到一对字符(S和T两个字符串中相同位置的两个字符),检查它们是否在map中出现,以及map信息是否一致。
这里,一定要注意的是只用一个map还不够,比如说S=aa和T=ab,如果只map[T]->S的话,在第一个字符上map[a] = a, 第二个字符上检查map中没有b,所以增加map[b] = a,这样会出现两个字符map到同一个字符,所以不仅要检查map的所有key还要检查value。一个简单的办法是再创建一个map[S]->T。
bool isIsomorphic(string s, string t) { if(s.length() != t.length()) return false; unordered_map<char, char> mapS; unordered_map<char, char> mapT; for(int i = 0; i < s.length(); ++i) { if(mapS.find(s[i]) != mapS.end()) { if(mapS[s[i]] != t[i]) return false; } else if(mapT.find(t[i]) != mapT.end()){ if(mapT[t[i]] != s[i]) return false; } else { mapS[s[i]] = t[i]; mapT[t[i]] = s[i]; } } return true; }