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 小时前
CentOS官方不维护版本,配置python升级方法,无损版
linux·python·centos
Gerardisite1 小时前
如何在微信个人号开发中有效管理API接口?
java·开发语言·python·微信·php
小毛驴8501 小时前
软件设计模式-装饰器模式
python·设计模式·装饰器模式
gfdhy2 小时前
【c++】哈希算法深度解析:实现、核心作用与工业级应用
c语言·开发语言·c++·算法·密码学·哈希算法·哈希
闲人编程2 小时前
Python的导入系统:模块查找、加载和缓存机制
java·python·缓存·加载器·codecapsule·查找器
百***06012 小时前
SpringMVC 请求参数接收
前端·javascript·算法
weixin_457760002 小时前
Python 数据结构
数据结构·windows·python
一个不知名程序员www3 小时前
算法学习入门---vector(C++)
c++·算法
合作小小程序员小小店3 小时前
web网页,在线%抖音,舆情,线性回归%分析系统demo,基于python+web+echart+nlp+线性回归,训练,数据库mysql
python·自然语言处理·回归·nlp·线性回归