Java函数实现判断两个字符串是否为同构的方法
发布时间:2023-10-09 05:24:53
两个字符串是否为同构的方法是通过比较两个字符串中字符的位置关系来判断的。如果两个字符串中字符在字符串中的位置关系相同,则认为这两个字符串是同构的。
要判断两个字符串是否为同构,可以使用一个HashMap来存储字符和其在字符串中的位置关系。遍历每个字符,将其和相应位置存入HashMap中。同时,比较两个字符串中对应位置的字符是否相同。如果两个字符串中对应位置的字符不相同,或者在HashMap中对应字符的位置不同,那么这两个字符串就不是同构的。
下面是Java实现的代码:
import java.util.HashMap;
public class StringIsomorphic {
public static boolean isIsomorphic(String s, String t) {
if (s.length() != t.length()) {
return false;
}
HashMap<Character, Integer> mapS = new HashMap<>();
HashMap<Character, Integer> mapT = new HashMap<>();
for (Integer i = 0; i < s.length(); i++) {
char charS = s.charAt(i);
char charT = t.charAt(i);
if (mapS.containsKey(charS) && mapT.containsKey(charT)) {
if (!mapS.get(charS).equals(mapT.get(charT))) {
return false;
}
} else if (!mapS.containsKey(charS) && !mapT.containsKey(charT)) {
mapS.put(charS, i);
mapT.put(charT, i);
} else {
return false;
}
}
return true;
}
public static void main(String[] args) {
String s1 = "egg";
String t1 = "add";
System.out.println(isIsomorphic(s1, t1)); // true
String s2 = "foo";
String t2 = "bar";
System.out.println(isIsomorphic(s2, t2)); // false
String s3 = "paper";
String t3 = "title";
System.out.println(isIsomorphic(s3, t3)); // true
}
}
上述代码中,通过两个HashMap mapS 和 mapT 来存储字符和其在字符串中的位置关系。遍历两个字符串,对于每个字符,如果HashMap中已经有该字符,则判断其位置是否匹配,如果不匹配则返回false;如果HashMap中没有该字符,则将该字符和位置存入HashMap中,同时,对另一个字符串做相同的操作。最后返回true,表示两个字符串是同构的。
以上是判断两个字符串是否为同构的Java函数实现的方法。
