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
Given
"egg"
, "add"
, return true.
Given
"foo"
, "bar"
, return false.
Given
"paper"
, "title"
, return true.
Solution:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public: | |
bool isIsomorphic(string s, string t) { | |
char map_s2t[128]={'\n'}; | |
memset(map_s2t, '\n', sizeof(map_s2t)); | |
char map_t2s[128]={'\n'}; | |
memset(map_t2s, '\n', sizeof(map_t2s)); | |
if(s.length()==0) | |
return true; | |
for(int i=0; i<s.length(); i++){ | |
char schar=s[i]; | |
char tchar=t[i]; | |
if(map_s2t[schar]=='\n'&&map_t2s[tchar]=='\n'){ | |
map_s2t[schar]=tchar; | |
map_t2s[tchar]=schar; | |
continue; | |
} | |
if(map_s2t[schar]==tchar&&map_t2s[tchar]==schar) | |
continue; | |
else | |
return false; | |
} | |
return true; | |
} | |
}; |
Round 2 solution:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public: | |
bool isIsomorphic(string s, string t) { | |
if(s.length()!=t.length()) | |
return false; | |
if(s==t||(s.empty()&&t.empty())) | |
return true; | |
unordered_map<int, int> myMap1; | |
unordered_map<int, int> myMap2; | |
for(int i=0; i<s.length(); i++){ | |
if(myMap1[s[i]]==0&&myMap2[t[i]]==0){ | |
myMap1[s[i]]=t[i]; | |
myMap2[t[i]]=s[i]; | |
} | |
else | |
if(myMap1[s[i]]!=t[i]||myMap2[t[i]]!=s[i]) | |
return false; | |
} | |
return true; | |
} | |
}; |
No comments:
Post a Comment