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();
}
}
本文详细阐述了如何通过数字映射的方法,判断两个字符串是否具有同构性,即字符间的替换关系是否一致。通过将字符串转换为数字序列并比较,我们能有效地解决同构性检测的问题,此方法适用于编程基础的理解和应用。
1413

被折叠的 条评论
为什么被折叠?



