同构字符串

Leetcode上原题如下:

给定两个字符串 s 和 t,判断它们是否是同构的。

如果 s 中的字符可以被替换得到 t ,那么这两个字符串是同构的。

所有出现的字符都必须用另一个字符替换,同时保留字符的顺序。两个字符不能映射到同一个字符上,但字符可以映射自己本身。

第一种思路:哈希表

建立两个字符串中字母的映射。由于题目要求两个字符不能映射到同一个字符上,因此,建立两个哈希表,前一个哈希表的键值对和后一个哈希表的键值对刚好相反。

public boolean isIsomorphic(String s, String t){
    if(s.length() != t.length()){
        return false;
    }
    
    Map<Character,Character> map = new HashMap<>();
    Map<Character,Character> antiMap = new HashMap<>();
    
    int len = s.length();
    for(int i = 0; i < len; i++){
        char c = s.charAt(i);
        char r = t.charAt(i);
        if(map.containsKey(c)){
            char value = map.get(c);
            if(value != r){
                return false;
            }
        }else{
            if(antiMap.containsKey(r))
                return false;
            else{
                map.put(c,r);
                antiMap.put(r,c);
            }
        }
    }
    return true;
}

第二种思路:查找索引

public boolean isIsomorphic(String s, String t){
    if(s.length() != t.length())
        return false;
    
    char[] ch1 = s.toCharArray();
    char[] ch2 = t.toCharArray();
    
    int len = s.length();
    for(int i = 0; i < len; i++){
        if(s.indexOf(ch1[i]) != t.indexOf(ch2[i]))
            return false;
    }
    return true;
}

猜你喜欢

转载自www.cnblogs.com/Chsy/p/11961749.html