直接的方法就是想到了用两个hashmap 记录每个的id,即第几个出现的unique字母,再出现这个字母的时候 它的id就去map里面查看
出现新的字母 id ++
然后判断此时这两个string的对应字母的id是否一致
public class Solution {
public boolean isIsomorphic(String s, String t) {
if ( s == null || t == null )
return true;
int length = s.length();
HashMap<Character,Integer>sset = new HashMap<Character,Integer>();
HashMap<Character,Integer>tset = new HashMap<Character,Integer>();
int counts = 0;
int countt = 0;
int curS = counts;
int curT = countt;
for ( int i = 0; i < length; i ++ ){
if ( !sset.containsKey(s.charAt(i)) ){
counts ++;
sset.put( s.charAt(i), counts );
}
curS = sset.get(s.charAt(i));
if ( !tset.containsKey(t.charAt(i)) ){
countt ++;
tset.put( t.charAt(i), countt);
}
curT = tset.get(t.charAt(i));
if ( curS != curT )
return false;
}
return true;
}
}
看了答案发现简便算法:
只用记录每个字母出现的最后位置 然后每遇到一个字母 就对比此位置是否一样 用了两个256数组
注意!!!因为数组初始化成了0 所以为了和还没有遇到过这个字母区别开,每次fuzhi要加1
public class Solution {
public boolean isIsomorphic(String s, String t) {
int [] sArr = new int [ 256 ];
int [] tArr = new int [ 256 ];
for ( int i = 0; i < s.length(); i ++ ) {
if ( sArr[s.charAt(i)] != tArr[t.charAt(i)] )
return false;
sArr[s.charAt(i)] = i + 1;
tArr[t.charAt(i)] = i + 1;
}
return true;
}
}