题目:
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.
分析1(推荐):
class Solution {
public boolean isIsomorphic(String s, String t) {
//isomorphic所谓同构就是说有相同的结构
//就是两个字符串长度相同,并且每一位被相同的字符替代后所得的新字符串相等,这样的字符串是同构字符串
//思路:采用数组(256个:所有ACSII字符)记录匹配次数,另一个数组用于表示是否匹配成功
if(s.length()!=t.length()){
return false;
}
char [] mapping= new char[256];
boolean [] mapped=new boolean[256];
char[] chs=s.toCharArray();
char[] cht=t.toCharArray();
for(int i=0;i<s.length();i++){
char cs=chs[i];
char ct=cht[i];
//没有匹配过
if(mapping[cs]==0){
if(mapped[ct]){
return false;
}
mapping[cs]=ct;
mapped[ct]=true;
}else{
//s中的字符之前已经匹配过,只需要判断当前是否满足之前的匹配关系
if(mapping[cs]!=ct){
return false;
}
}
}
return true;
}
}
分析2(推荐):
class Solution {
public boolean isIsomorphic(String s, String t) {
//isomorphic所谓同构就是说有相同的结构
//就是两个字符串长度相同,并且每一位被相同的字符替代后所得的新字符串相等,这样的字符串是同构字符串
//思路:采用两个HashMap分别存储s中的字符在t中的对应字母,t中的字符在s中对应的字符,形成一种映射关系
if(s.length()!=t.length()){
return false;
}
HashMap<Character,Character> hmS=new HashMap<Character,Character>();
HashMap<Character,Character> hmT=new HashMap<Character,Character>();
for(int i=0;i<s.length();i++){
//如果hmS中字符映射关系不对应t中的字符,直接返回false
if(hmS.containsKey(s.charAt(i))){
//对应的映射关系在t中不匹配其对应位置的字符
if(hmS.get(s.charAt(i))!=t.charAt(i)){
return false;
}
}else{
//判断hmT是否包含,如果已经包含该字符,说明不匹配,直接返回
if(hmT.containsKey(t.charAt(i))){
return false;
}
//说明之前都未存入对方的映射关系
//则分别添加进彼此的映射表
hmS.put(s.charAt(i),t.charAt(i));
hmT.put(t.charAt(i),s.charAt(i));
}
}
return true;
}
}