abb和egg title和paper是同构字符串,foo和bar就不是同构字符串
什么是同构字符串?
两个个字符串的每个字母都匹配同一个映射关系,比如egg -> add的映射关系就是:e->a, g->d; foo与bar显然不满足,因为o->a同事o->r;paper和title满足,p->t, a->i, e->l, r->e。
所以需要一个map来存放映射关系,两个字符串从头开始比较的时候,如果map中没有映射关系那么就插入一对字符映射,如果有就比较映射关系是否相同,如果不同就说明不是同构字符串返回false,知道所有的映射关系都满足就返回true。
import java.util.*;
public class TongGouString {
public static void main(String[] args) {
// TODO Auto-generated method stub
String s="abb";
String t="egg";
System.out.println(isIsomorphic( s, t));//true
String s1="paper";
String t1="title";
System.out.println(isIsomorphic( s1, t1));//true
String s2="foo";
String t2="bar";
System.out.println(isIsomorphic( s2, t2));//false
String s3="abcde";
String t3="bcjfm";
System.out.println(isIsomorphic( s3, t3));//true
String s4="aa";
String t4="ab";
System.out.println(isIsomorphic( s4, t4));//false
}
public static boolean isIsomorphic(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;
}
}