LeetCode 242. 有效的字母异位词(Valid Anagram)

242. 有效的字母异位词

LeetCode242. Valid Anagram

题目描述
给定两个字符串 s 和 t ,编写一个函数来判断 t 是否是 s 的一个字母异位词。

示例 1:
输入: s = "anagram", t = "nagaram"
输出: true

示例 2:
输入: s = "rat", t = "car"
输出: false

说明:
你可以假设字符串只包含小写字母。

进阶:
如果输入字符串包含 unicode 字符怎么办?你能否调整你的解法来应对这种情况?

Java 实现

class Solution {
    // 个人思路
    public boolean isAnagram1(String s, String t) {
        if (s == null || t == null) {
            return s == null && t == null;
        }
        if (s.length() != t.length()) {
            return false;
        }
        Map<Character, Integer> map = new HashMap<>();
        for (int i = 0; i < s.length(); i++) {
            if (map.containsKey(s.charAt(i))) {
                map.put(s.charAt(i), map.get(s.charAt(i)) + 1);
            } else {
                map.put(s.charAt(i), 1);
            }
        }
        for (int i = 0; i < t.length(); i++) {
            if (map.containsKey(t.charAt(i))) {
                map.put(t.charAt(i), map.get(t.charAt(i)) - 1);
            }
        }
        for (Character character : map.keySet()) {
            if (map.get(character) != 0) {
                return false;
            }
        }
        return true;
    }
    
    // 参考思路
    public boolean isAnagram(String s, String t) {
        if (s == null || t == null) {
            return s == null && t == null;
        }
        if (s.length() != t.length()) {
            return false;
        }
        int[] res = new int[26];
        for (int i = 0; i < s.length(); i++) {
            res[s.charAt(i) - 'a']++;
        }
        for (int j = 0; j < t.length(); j++) {
            res[t.charAt(j) - 'a']--;
        }
        for (int i = 0; i < s.length(); i++) {
            if (res[s.charAt(i) - 'a'] != 0) {
                return false;
            }
        }
        return true;
    }
}

参考资料

原文地址:https://www.cnblogs.com/hgnulb/p/10806647.html