Solution Code
C#
public class Solution {
public bool IsIsomorphic(string s, string t) {
int len = s.Length;
bool isIso = true;
int[] mapping = new int[130];
int[] mappedTo = new int[130];
for (int i = 0; i < len; i++) {
if (mapping[s[i]] > 0) {
int val = mapping[s[i]];
if ((int)t[i] != val) {
isIso = false;
break;
}
} else {
if (mappedTo[t[i]] > 0) {
isIso = false;
break;
}
mapping[s[i]] = t[i];
mappedTo[t[i]] = s[i];
}
}
return isIso;
}
}
C++
class Solution {
public:
bool isIsomorphic(string s, string t) {
int len = s.size();
bool isIso = true;
unordered_map<char, char> mapping;
unordered_map<char, char> mappedTo;
for (int i = 0; i < len; i++) {
if (mapping.count(s[i])) {
char ch = mapping[s[i]];
if (t[i] != ch) {
isIso = false;
break;
}
} else {
if (mappedTo.count(t[i])) {
isIso = false;
break;
}
mapping[s[i]] = t[i];
mappedTo[t[i]] = s[i];
}
}
return isIso;
}
};
Java
class Solution {
public boolean isIsomorphic(String s, String t) {
int len = s.length();
boolean isIso = true;
int[] mapping = new int[130];
int[] mappedTo = new int[130];
for (int i = 0; i < len; i++) {
if (mapping[s.codePointAt(i)] > 0) {
int val = mapping[s.codePointAt(i)];
if (t.codePointAt(i) != val) {
isIso = false;
break;
}
} else {
if (mappedTo[t.codePointAt(i)] > 0) {
isIso = false;
break;
}
mapping[s.codePointAt(i)] = t.codePointAt(i);
mappedTo[t.codePointAt(i)] = s.codePointAt(i);
}
}
return isIso;
}
}