This problem can be solved by using a hash map to store the mapping between the two strings. I initially thought it only contained lowercase letters, but it actually includes all ASCII characters. I started with one hash map, but since the mapping needs to be one-to-one, I ended up using two.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
| class Solution {
public:
bool isIsomorphic(string s, string t) {
if (s.length() != t.length()) return false;
char hash_s[256];
char hash_t[256];
memset(hash_s, NULL, 256);
memset(hash_t, NULL, 256);
for (int i = 0; i < s.length(); i++) {
if (NULL == hash_s[s[i]] && NULL == hash_t[t[i]]) {
hash_s[s[i]] = t[i];
hash_t[t[i]] = s[i];
}
else {
if (hash_s[s[i]] != t[i] || hash_t[t[i]] != s[i]) return false;
}
}
return true;
}
};
|