[LeetCode] 205. Isomorphic Strings同構字串
阿新 • • 發佈:2019-02-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.
分析:判斷字串s能否通過字元替換得到字串t
解題思路:將字串s和字串t的對應關係用map來儲存,當發現該字元在map中已經存在,則將map中的值取出看與當前字串t的字元是否一樣。如果不存在則需要將s與t的對應字元存入map中。需要兩次比較過程!
public class Isomorphic_Strings {
public boolean isIsomorphic(String s, String t) {
return doCheck(s,t)&&doCheck(t,s);
}
public boolean doCheck(String s,String t){
Map<Character,Character> map = new HashMap<Character,Character>();
if(s.length()!=t.length())return false;
for(int i=0 ;i<s.length();i++){
char sChar = s.charAt(i);
char tChar = t.charAt(i);
if(!map.containsKey(sChar)){
map.put(sChar, tChar);
}else{
char cCompare = map.get(sChar);
if(cCompare!=tChar){
return false;
}
}
}
return true;
}
}