https://leetcode.com/problems/isomorphic-strings/description/
题目描述: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;
}
}