-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathIsomorphicStrings.cpp
More file actions
41 lines (41 loc) · 1.4 KB
/
IsomorphicStrings.cpp
File metadata and controls
41 lines (41 loc) · 1.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
class Solution {
public:
bool isIsomorphic(string s, string t) {
int size = s.size();
if(size != t.size()){
return false;
}
unordered_map<char, char> map;
//charSet is used to avoid two characters may map to the same character
set<char> charSet;
//use t's character to replace s'
for(int i = 0; i < size; i++){
//we should use t[i] to replace s[i]
if(s[i] != t[i]){
//we have not replace s[i] before.
if(map.find(s[i]) == map.end()){
//we have not use t[i] to replace any of s' character
if(charSet.find(t[i]) == charSet.end()){
map[s[i]] = t[i];
charSet.insert(t[i]);
}else{
return false;
}
}else{
//the same s[i] maps to different t[i]
if(map[s[i]] != t[i]){
return false;
}
}
}else{
//we have replace s[i] before, but the previous is not equal to t[i]
if(map.find(s[i]) != map.end() && map[s[i]] != t[i]){
return false;
}
map[s[i]] = t[i];
charSet.insert(t[i]);
}
}
return true;
}
};