首页 > 技术文章 > LC-242

zwtblog 2022-03-18 14:49 原文

利用ASCII码构成哈希表来映射

和这题类似:

回到本题:242. 有效的字母异位词

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

注意:若 s 和 t 中每个字符出现的次数都相同,则称 s 和 t 互为字母异位词。

Java实现:

public class LC242 {
    public static void main(String[] args) {
        String s = "anagram";
        String t = "nagaram";
        System.out.println(isAnagram(s, t));
    }

    public static boolean isAnagram(String s, String t) {
        char[] chars = s.toCharArray();
        char[] chart = t.toCharArray();
        int sLength = chars.length, tLength = chart.length;
        int[] hash = new int[128];
        for (int i = 0; i < tLength; i++) {
            hash[chart[i]]--;
        }
        for (int i = 0; i < sLength; i++) {
            hash[chars[i]]++;
        }
        for (int i = 0; i < 128; i++) {
            if (hash[i] != 0) {
                return false;
            }
        }
        return true;
    }
}

Python实现:附带优化成26个字符

class Solution:
    def isAnagram(self, s: str, t: str) -> bool:
        if len(s) != len(t):
            return False
        hashRecord = [0] * 26
        for i in s:
            hashRecord[ord(i) - ord('a')] += 1;
        for j in t:
            hashRecord[ord(j) - ord('a')] -= 1;
        for item in hashRecord:
            if item != 0:
                return False
        return True

推荐阅读