🌗 205. 同构字符串

吞佛童子2022年6月20日
  • algorithm
  • hash
  • map
  • set
小于 1 分钟

🌗 205. 同构字符串

难度: 🌗

问题描述

img_1.png


解法

class Solution {
    public boolean isIsomorphic(String s, String t) {
        // 思路:
        // map 存储 s -> t 的映射关系
        // set 存储 s-> t 的映射目标是否有重复
        int m = s.length();
        // 题意已经表明,两者长度相等,无需特判
        if(m == 1) {
            return true;
        }
        HashMap<Character, Character> map = new HashMap<>();
        HashSet<Character> set = new HashSet<>();
        for(int i = 0; i < m; i ++) {
            char c = s.charAt(i);
            char d = t.charAt(i);
            if(!map.containsKey(c)) {
                // 尝试将 c -> d 的映射放入 map 
                if(!set.contains(d)) {
                    map.put(c, d);
                    set.add(d);
                } else {
                    return false;
                }
            } else {
                char dExp = map.get(c);
                if(d != dExp) {
                    return false;
                }
            }
        }
        return true;
    }
}

输出

img.png

上次编辑于: 2022/6/20 下午8:24:47
贡献者: liuxianzhishou