一、問題描述
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.
二、問題分析
顯然是一種map的關係,可以使用HashMap來處理,比較簡單。
三、Java AC代碼
public boolean isIsomorphic(String s, String t) {
HashMap<Character, Character> map = new HashMap<Character, Character>();
if (s.length()!=t.length()) {
return false;
}
char chs;
char cht;
for(int i=0;i<s.length();i++){
chs = s.charAt(i);
cht = t.charAt(i);
if (!map.containsKey(chs)) {
if (map.values().contains(cht)) {
return false;
}
map.put(chs, cht);
}else {
if (map.get(chs).equals(cht)) {
continue;
}else {
return false;
}
}
}
return true;
}