題目描述:
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.
解題思路
使用兩個char數組sm,st sm[s[i]] = t[i]; st[t[i]] = s[i];
public class Solution {
public boolean isIsomorphic(String s, String t) {
if(s==null || t==null)
return false;
if(s.length()!=t.length())
return false;
char[] sa = s.toCharArray();
char[] ta = t.toCharArray();
char[] sm = new char[256];
char[] tm = new char[256];
for(int i = 0 ; i<sa.length;i++){
char sc = sa[i];
char tc = ta[i];
if(sm[sc] == 0 && tm[tc]==0){
sm[sc] = tc;
tm[tc] = sc;
}else{
if(sm[sc]!=tc || tm[tc]!=sc){
return false;
}
}
}
return true;
}
}