205. Isomorphic Strings

来源:互联网 发布:浙江旅游数据 编辑:程序博客网 时间:2024/05/20 15:12

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.

问题:判断两个字符串是否同构,假定字符串长度相等

思想:(1)借助map<a1,a2>,字符串s和t,相当于两个映射,从s1->s2和从s2->s1的,比如egh和add,  ea是一对 gd是一对 但是hd又是一对,此刻不满足: 但是map比较耗时

如果map.contains(a1)且map.get(a1)!=a2,则映射不成立

如果map里没有a1,但是有值a2表明先gd又来hd这种情况。

 public boolean isIsomorphic(String s, String t) {//利用map         if(s==null&&t==null||s.length()==0&&t.length()==0) return true;  if(s==null||t==null||s.length()!=t.length()) return false;  Map<Character,Character> map=new HashMap();  map.put(s.charAt(0), t.charAt(0));  for(int i=1;i<s.length();i++){  char a1=s.charAt(i);  char a2=t.charAt(i);  if(map.containsKey(a1)){  if(map.get(a1)!=a2) return false;  }else if(map.containsValue(a2)){  return false;  }  else{  map.put(a1, a2);  }  }        return true;    }
(2)高效的办法--数组,只应用于ASCII码
数组:字符a1 a2在两个字符串s1 s2中最后出现的位置,如果之前的存储位置不同,那么很显然两者是不同构的

  public boolean  isIsomorphic2(String s,String t){  int[] pos=new int[512];  for(int i=0;i<s.length();i++){  if(pos[s.charAt(i)]!=pos[t.charAt(i)+256]) return false;  pos[s.charAt(i)]=i+1;//因为pos初始化时全是0,如果=i的话,  //两个字符串首个字符同构存的值是0,和没出现没差,所以=i+1  pos[t.charAt(i)+256]=i+1;    }  return true;  }


0 0