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.
题目解析:该题要看两组字符串是不是成对应关系,我的想法是将其变成数字组成的字符串,然后判断是否相等,该题没什么难点,关键在于字符串的拼接不要用String
代码:
public class Solution {
public boolean isIsomorphic(String s, String t) {
String s1=getNumber(s);
String s2=getNumber(t);
if(s1.equals(s2)){
return true;
}else{
return false;
}
}
public static String getNumber(String st){
Map<Character,Integer> map =new HashMap<Character,Integer>();
char[] ch=st.toCharArray();
StringBuilder re=new StringBuilder();
for(int i=0,j=0;i<ch.length;i++){
if(!map.containsKey(ch[i])){
map.put(ch[i], j);
j++;
re=re.append(map.get(ch[i]));
}else{
re=re.append(map.get(ch[i]));
}
}
return re.toString();
}
}