Question
Given strings s and t, determine if they are isomorphic.
The strings is isomorphic if the characters in s can is replaced to get t.
All occurrences of a character must is replaced with another character while preserving the order of characters. No, characters may map to the same character and a character may map to itself.
For example,
Given "egg"
, "add"
return True.
Given "foo"
, "bar"
return FALSE.
Given "paper"
, "title"
return True.
Solution 1
Use HashMap, remember to check both key and value. Time complexity O (n^2), Space cost O (n).
Hashmap.containsvalue costs O (n)
1 Public classSolution {2 Public Booleanisisomorphic (string s, String t) {3 if(s = =NULL|| t = =NULL)4 return false;5 if(S.length ()! =t.length ())6 return false;7 if(S.length () ==0 && t.length () ==0)8 return true;9 intLength =s.length ();TenMap<character, character> map =NewHashmap<character, character>(); One for(inti = 0; i < length; i++) { A CharTMP1 =S.charat (i); - CharTMP2 =T.charat (i); - if(Map.containskey (TMP1)) { the if(Map.get (TMP1)! =tmp2) - return false; -}Else if(Map.containsvalue (TMP2)) { - return false; +}Else { - map.put (TMP1, TMP2); + } A } at return true; - } -}
Solution 2
Use extra space to reduce time complexity.
1 Public classSolution {2 Public Booleanisisomorphic (string s, String t) {3 if(s = =NULL|| t = =NULL)4 return false;5 if(S.length ()! =t.length ())6 return false;7 if(S.length () ==0 && t.length () ==0)8 return true;9 intLength =s.length ();TenMap<character, character> map =NewHashmap<character, character>(); Oneset<character> counts =NewHashset<character>(); A for(inti = 0; i < length; i++) { - CharTMP1 =S.charat (i); - CharTMP2 =T.charat (i); the if(Map.containskey (TMP1)) { - if(Map.get (TMP1)! =tmp2) - return false; -}Else if(Counts.contains (TMP2)) { + return false; -}Else { + map.put (TMP1, TMP2); A Counts.add (TMP2); at } - } - return true; - } -}
Isomorphic Strings Solutions