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.
public boolean isIsomorphic(String s, String t) { if(s.length() != t.length()) return false; Map<Character, Character> mapS = new HashMap<>(), mapT = new HashMap<>(); for(int i=0; i<s.length(); i++) { char cs = s.charAt(i); char ct = t.charAt(i); if(!mapS.containsKey(cs)) { mapS.put(cs, ct); } else if(mapS.get(cs) != ct) { return false; } if(!mapT.containsKey(ct)) { mapT.put(ct, cs); } else if(mapT.get(ct) != cs) { return false; } } return true; }
C++的代码:
bool isIsomorphic(string s, string t) { if(s.size() != t.size()) return false; unordered_map<char, char> ms, mt; for(size_t i=0; i<s.size(); i++) { if(ms.count(s[i])) { if(ms[s[i]] != t[i]) return false; } else { ms[s[i]] = t[i]; } if(mt.count(t[i])) { if(mt[t[i]] != s[i]) return false; } else { mt[t[i]] = s[i]; } } return true; }