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.
public boolean isIsomorphic(String s, String t) {
if(s.length()!=t.length()) return false;
HashMap<Character, Character> map = new HashMap<Character, Character>();
for(int i = 0;i<s.length();i++){
char a = s.charAt(i);
char b = t.charAt(i);
if(map.containsKey(a)){
if(map.get(a).equals(b)) continue;
else return false;
}
else{
if(!map.containsValue(b)) map.put(a,b);
else return false;
}
}
return true;
}
总结:用了hashmap
public boolean isIsomorphic(String s, String t) {
int [] m = new int[512];
for(int i=0;i<s.length();i++){
if(m[s.charAt(i)] != m[t.charAt(i)+256]) return false;
m[s.charAt(i)] = m[t.charAt(i)+256] =i+1;
}
return true;
}
直接数组索引,归根结底看上一组出现的是不是同一个数字。还是不要用put