LeetCode242 Valid Anagram

本文介绍了一种用于判断两个字符串是否为字母异位词的算法,并提供了详细的Java实现代码。该方法通过统计每个字符串中字符出现的次数来进行比较,适用于仅包含小写字母的情况。同时,文章还讨论了如何应对Unicode字符集的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目

Given two strings s and t, write a function to determine if t is an anagram of s.

For example,
s = “anagram”, t = “nagaram”, return true.
s = “rat”, t = “car”, return false.

Note:
You may assume the string contains only lowercase alphabets.

解法

和387题类似,都可以使用统计每个字符出现的个数的方式来比较,只要所有字符出现的次数相同且两个字符串不行等,则返回true。需要注意的是,根据leetcode的评价标准,两个空串返回true。

public boolean isAnagram(String s, String t) {
        int lenS = s.length();
        int lenT = t.length();
        if (lenS == 0 && lenT == 0) return true;
        if (lenS == 1 && lenT == 1 && s.equals(t)) return true;
        if (lenS != lenT) return false;
        if (s.equals(t)) return false;
        int[] recordS = new int[26];
        int[] recordT = new int[26];
        for (int i = 0; i < lenS; i++) {
            char c1 = s.charAt(i);
            char c2 = t.charAt(i);
            int index1 = c1 - 'a';
            int index2 = c2 - 'a';
            recordS[index1]++;
            recordT[index2]++;
        }

        for (int i = 0; i < 26; i++)
            if (recordS[i] != recordT[i])
                return false;

        return true;
    }

扩展

如果需要加入unicode字符,那么上一种方式就不可行,因为小写字母只有26个,但unicode字符有6万多个,使用数组来一一对应开销过大。这时就可以使用hashmap来存储键值对,因为hashmap自动去重,可以参考我的上一篇博客.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值