🌗 242. 有效的字母异位词

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

🌗 242. 有效的字母异位词

难度: 🌗

问题描述

img_1.png


解法

class Solution {
    public boolean isAnagram(String s, String t) {
        // 思路:
        // HashMap | 数组 做 map
        int len = s.length();
        if(t.length() != len) {
            return false;
        }
        // 遍历 s 添加进 map
        HashMap<Character, Integer> map = new HashMap<>();
        for(char c : s.toCharArray()) {
            if(!map.containsKey(c)) {
                map.put(c, 1);
            } else {
                int count = map.get(c);
                count ++;
                map.put(c, count);
            }
        }
        // 遍历 t 将元素从 map 中去除
        for(char c : t.toCharArray()) {
            if(!map.containsKey(c)) {
                return false;
            } else {
                int count = map.get(c);
                count --;
                if(count == 0) {
                    map.remove(c);
                } else {
                    map.put(c, count);
                }
            }
        }
        if(map.isEmpty()) {
            return true;
        } else {
            return false;
        }
    }
}

输出

img.png

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