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;
    }
}
相关推荐
xwill*4 小时前
分词器(Tokenizer)-sentencepiece(把训练语料中的字符自动组合成一个最优的子词(subword)集合。)
开发语言·pytorch·python
咖啡の猫4 小时前
Python列表的查询操作
开发语言·python
Chiandra_Leong4 小时前
Python-Pandas、Numpy
python·pandas
BoBoZz194 小时前
ParametricObjectsDemo多种参数曲面展示及面上部分点法线展示
python·vtk·图形渲染·图形处理
Savior`L5 小时前
二分算法及常见用法
数据结构·c++·算法
quikai19815 小时前
python练习第三组
开发语言·python
mmz12076 小时前
前缀和问题(c++)
c++·算法·图论
ULTRA??6 小时前
初学protobuf,C++应用例子(AI辅助)
c++·python
CHANG_THE_WORLD6 小时前
Python 字符串全面解析
开发语言·python
努力学算法的蒟蒻6 小时前
day27(12.7)——leetcode面试经典150
算法·leetcode·面试