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;
    }
}
相关推荐
AI视觉网奇几秒前
pycharm 最新版上一次编辑位置
python
2401_8288906423 分钟前
使用 BERT 实现意图理解和实体识别
人工智能·python·自然语言处理·bert·transformer
先做个垃圾出来………44 分钟前
差分数组(Difference Array)
java·数据结构·算法
hansang_IR1 小时前
【题解】洛谷 P4286 [SHOI2008] 安全的航线 [递归分治]
c++·数学·算法·dfs·题解·向量·点积
乐迪信息1 小时前
乐迪信息:AI摄像机在智慧煤矿人员安全与行为识别中的技术应用
大数据·人工智能·算法·安全·视觉检测
多恩Stone2 小时前
【3DV 进阶-2】Hunyuan3D2.1 训练代码详细理解下-数据读取流程
人工智能·python·算法·3d·aigc
xiaopengbc2 小时前
在 Python 中实现观察者模式的具体步骤是什么?
开发语言·python·观察者模式
Python大数据分析@2 小时前
python用selenium怎么规避检测?
开发语言·python·selenium·网络爬虫
ThreeAu.2 小时前
Miniconda3搭建Selenium的python虚拟环境全攻略
开发语言·python·selenium·minicoda·python环境配置