isomorphic strings


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 "egg", "add", return true.

Given "foo", "bar", return false.

Given "paper", "title", return true.

Note:
You may assume both s and t have the same length.


Solution:

1
2
3
4
5
6
7
8
9
10
11
public class {
public boolean isIsomorphic(String s, String t) {
int compare[] = new int[512];
for (int i=0; i<s.length(); i++) {
if (compare[s.charAt(i)] != compare[t.charAt(i)+256])
return false;
compare[s.charAt(i)] = compare[t.charAt(i)+256] = i + 1;
}
return true;
}
}

思想:位置相同的字母占据同样的槽(512分为两个256槽,一共256个ASCII码值),相同位置的槽的值不同时即是两个字符串出现了不匹配的情况。