205. Isomorphic Strings
问题描述:
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.
字符串同构问题,重点是字符映射。
同一位置上的字符相互映射
public boolean isIsomorphic(String s, String t) {
if(s==null || s.length()<=1)
return true;
HashMap<Character,Character> hm=new HashMap<Character,Character>();
for(int i=0;i<s.length();i++){
char ch1=s.charAt(i);
char ch2=t.charAt(i);
if(hm.containsKey(ch1)){
if(hm.get(ch1)==ch2)
continue;
else
return false;
}else{
if(hm.containsValue(ch2))
return false;
else
hm.put(ch1, ch2);
}
}
return true;
}