leetcode-有效的字母异位词

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

示例 1:

复制代码
输入: s = "anagram", t = "nagaram"
输出: true

示例 2:

复制代码
输入: s = "rat", t = "car"
输出: false

提示:

  • 1 <= s.length, t.length <= 5 * 104
  • st 仅包含小写字母

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

python 复制代码
class Solution:
    def isAnagram(self, s: str, t: str) -> bool:
        return Counter(s) == Counter(t)
        
python 复制代码
class Solution:
    def isAnagram(self, s: str, t: str) -> bool:

        return sorted(s)==sorted(t)
python 复制代码
class Solution:
    def isAnagram(self, s: str, t: str) -> bool:
        if len(s) != len(t):
            return False
        dic = defaultdict(int)
        for c in s:
            dic[c] += 1
        for c in t:
            dic[c] -= 1
        for val in dic.values():
            if val != 0:
                return False
        return True
python 复制代码
import java.util.HashMap;
import java.util.Map;

class Solution {
    public boolean isAnagram(String s, String t) {
        // 如果两个字符串的长度不相等,那么它们不可能是字母异位词,直接返回 false。
        if (s.length() != t.length()) {
            return false;
        }

        // 使用 HashMap 来存储字符串 s 中每个字符的出现次数。
        Map<Character, Integer> table = new HashMap<Character, Integer>();

        // 遍历字符串 s,将每个字符的出现次数记录在 HashMap 中。
        for (int i = 0; i < s.length(); i++) {
            char ch = s.charAt(i);
            // 如果字符 ch 在 table 中已经存在,则其值加 1;否则,将其初始值设为 1。
            table.put(ch, table.getOrDefault(ch, 0) + 1);
        }

        // 遍历字符串 t,减少 table 中对应字符的出现次数。
        for (int i = 0; i < t.length(); i++) {
            char ch = t.charAt(i);
            // 如果字符 ch 在 table 中存在,则减少其出现次数;如果不存在,则使用默认值 0 减 1。
            table.put(ch, table.getOrDefault(ch, 0) - 1);
            
            // 如果 table 中字符 ch 的出现次数小于 0,表示字符串 t 中该字符出现的次数比字符串 s 多。
            // 因此 s 和 t 不可能是字母异位词,直接返回 false。
            if (table.get(ch) < 0) {
                return false;
            }
        }

        // 如果遍历完成,且所有字符的计数都为 0,则 s 和 t 是字母异位词,返回 true。
        return true;
    }
}
相关推荐
databook13 小时前
Manim实现脉冲闪烁特效
后端·python·动效
程序设计实验室14 小时前
2025年了,在 Django 之外,Python Web 框架还能怎么选?
python
倔强青铜三15 小时前
苦练Python第46天:文件写入与上下文管理器
人工智能·python·面试
用户25191624271119 小时前
Python之语言特点
python
刘立军19 小时前
使用pyHugeGraph查询HugeGraph图数据
python·graphql
聚客AI21 小时前
🙋‍♀️Transformer训练与推理全流程:从输入处理到输出生成
人工智能·算法·llm
数据智能老司机1 天前
精通 Python 设计模式——创建型设计模式
python·设计模式·架构
大怪v1 天前
前端:人工智能?我也会啊!来个花活,😎😎😎“自动驾驶”整起!
前端·javascript·算法
数据智能老司机1 天前
精通 Python 设计模式——SOLID 原则
python·设计模式·架构
c8i1 天前
django中的FBV 和 CBV
python·django