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.
Note:
Assume both s and T have the same length.
This topic has a time limit, the key is how to optimize time.
I started with two for loops, so the time complexity is the square of N, but it has a test case and two strings are very long, so there's a exceeded. The code is as follows:
classSolution { Public: BOOLIsisomorphic (stringSstringt) {intLen =s.length (); //time complexity n squared, do not meet the requirements of the topic. for(size_t i =0; i < Len; i++) { for(size_t j = i +1; J < S.length (); J + +) { if((s[i] = = S[j] && t[i]! = t[j]) | | (S[i]! = S[j] && t[i] = =T[j])) { return false; } } } return true; }};
The above method does not work, it must reduce the complexity of time, and finally I think of a method: Using a <char, char> map map, for loop two arguments each char, if found that the corresponding relationship changed, Then it means that the two strings are not isomorphic. The time complexity is O (n) and the code is as follows:
classSolution { Public: BOOLIsisomorphic (stringSstringt) {intLen =s.length (); Map<Char,Char>m; Map<Char,Char>m2; for(size_t i =0; i < Len; i++) { if(M.find (s[i]) = =M.end ()) {M[s[i]]=T[i]; }Else if(M[s[i]]! =T[i]) { return false; } if(M2.find (t[i]) = =M2.end ()) {M2[t[i]]=S[i]; }Else if(M2[t[i]]! =S[i]) { return false; } } return true; }};
205 Isomorphic Strings