两个个字符串的每个字母都匹配同一个映射关系,比如egg -> add的映射关系就是:e->a, g->d; foo与bar显然不满足,因为o->a同事o->r;paper和title满足,p->t, a->i, e->l, r->e。现在用map保存映射关系
方法一:
public static boolean isIsomorphic(String s, String t) {
Map<Character,Integer> map_1 = new HashMap<Character,Integer>();
Map<Character,Integer> map_2 = new HashMap<Character,Integer>();
if(s.length() != t.length())
return false;
for(int i = 0;i<s.length();i++){
if((!map_1.containsKey(s.charAt(i))) && (!map_2.containsKey(t.charAt(i)))){//map全不包含
map_1.put(s.charAt(i), i);
map_2.put(t.charAt(i), i);
}else if(map_1.containsKey(s.charAt(i)) && map_2.containsKey(t.charAt(i))){//map全部包含
if(map_1.get(s.charAt(i)) != map_2.get(t.charAt(i)))
return false;
}
else //一个包含,一个不包含
return false;
}
return true;
}
方法二:不能判断egg ddd
public static boolean isIsomorphic_2(String s, String t) {
Map <Character,Character> map=new HashMap<Character, Character>();
if(s.length()!=t.length()) return false;
for(int i=0;i<s.length();i++){
if(map.containsKey(s.charAt(i))){
if( map.get(s.charAt(i))!=t.charAt(i))
return false;
}else{
map.put(s.charAt(i), t.charAt(i));
}
}
return true;
}