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.
At first I thought of replace the char in s and check whether the two strings match after that.
But in case of s="ab" t="aa"
, since one char has already been registered, it cannot be replace by a new one.
That is to say, there should be a one-on-one relationship between the map of 2 chars in 2 strings.
One normal way is to use 2 HashMaps which cost more space.
The other is also to construct 2 relation mapping but as a 512-sized int array (ascii table: 256 in size), so string s takes up 0-255, string t takes up 256-511
The mapping is done by setting the 2 chars (in each string) the index of occurrence. (since the int array is initiated to 0, we record i+1)
class Solution {
public boolean isIsomorphic(String s, String t) {
if(s.length()!=t.length()) return false;
if(s.equals(t)) return true;
int[] m = new int[512];
int len=s.length();
for(int i=0;i<len;i++){
if(m[s.charAt(i)]!=m[t.charAt(i)+256]) return false;
m[s.charAt(i)]=i+1;
m[t.charAt(i)+256]=i+1;
}
return true;
}
}