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.
思路:兩個hashMap分別存放s to t and t to s。如果不是一一對應,則返回.hashMap實現可以數組,也可以是hashMap。
public class Solution {
public boolean isIsomorphic(String s, String t) {
if(s==null||t==null||s.length()!=t.length()) return false;
Map<Character, Character> sTot = new HashMap<>(26);
Map<Character, Character> tTos = new HashMap<>(26);
for(int i=0; i<s.length(); i++){
if (sTot.containsKey(s.charAt(i))){
if (sTot.get(s.charAt(i))!=t.charAt(i)) return false;
}else{
sTot.put(s.charAt(i),t.charAt(i));
}
if (tTos.containsKey(t.charAt(i))){
if (tTos.get(t.charAt(i))!=s.charAt(i)) return false;
}else{
tTos.put(t.charAt(i),s.charAt(i));
}
}
return true;
}
}