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;
    }
}
相关推荐
老胖闲聊1 小时前
Python Copilot【代码辅助工具】 简介
开发语言·python·copilot
Blossom.1181 小时前
使用Python和Scikit-Learn实现机器学习模型调优
开发语言·人工智能·python·深度学习·目标检测·机器学习·scikit-learn
曹勖之2 小时前
基于ROS2,撰写python脚本,根据给定的舵-桨动力学模型实现动力学更新
开发语言·python·机器人·ros2
lyaihao3 小时前
使用python实现奔跑的线条效果
python·绘图
int型码农3 小时前
数据结构第八章(一) 插入排序
c语言·数据结构·算法·排序算法·希尔排序
UFIT3 小时前
NoSQL之redis哨兵
java·前端·算法
喜欢吃燃面3 小时前
C++刷题:日期模拟(1)
c++·学习·算法
SHERlocked933 小时前
CPP 从 0 到 1 完成一个支持 future/promise 的 Windows 异步串口通信库
c++·算法·promise
ai大师3 小时前
(附代码及图示)Multi-Query 多查询策略详解
python·langchain·中转api·apikey·中转apikey·免费apikey·claude4
怀旧,3 小时前
【数据结构】6. 时间与空间复杂度
java·数据结构·算法