栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

leetcode:242. 有效的字母异位词

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

leetcode:242. 有效的字母异位词

242. 有效的字母异位词

来源:力扣(LeetCode)

链接: https://leetcode.cn/problems/valid-anagram/

给定两个字符串 s 和 t ,编写一个函数来判断 t 是否是 s 的字母异位词。
注意:若 s 和 t 中每个字符出现的次数都相同,则称 s 和 t 互为字母异位词。

示例 1:

输入: s = "anagram", t = "nagaram"
输出: true

示例 2:

输入: s = "rat", t = "car"
输出: false

提示:

  • 1 <= s.length, t.length <= 5 ∗ 1 0 4 5 * 10^4 5∗104
  • s 和 t 仅包含小写字母

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

解法
  • 排序:二者排序之后挨个元素进行比较;
  • 哈希表:首先判断二者的长度是否相同,如果长度不同的话直接返回false;另外用一个哈希表进行比存储遍历的结构,key是元素,value是元素出现的次数;之后再遍历另一个字符串,如果元素在哈希表中,将次数减1,如果减到负数,直接返回false,如果不在哈希表中,也直接返回false;遍历到最后,看一下哈希表中每个key对应的次数是否为0;
代码实现 排序

使用列表自带的性质;
python实现

class Solution:
    def isAnagram(self, s: str, t: str) -> bool:
        return sorted(s) == sorted(t)

c++实现

class Solution {
public:
    bool isAnagram(string s, string t) {
        if (s.size() != t.size())
            return false;
        
        sort(s.begin(), s.end());
        sort(t.begin(), t.end());

        for (int i=0; i
            if (s[i] != t[i])
                return false;
        }
        return true;
    }
};

复杂度分析

  • 时间复杂度: O ( N l o g N ) O(NlogN) O(NlogN)
  • 空间复杂度: O ( l o g N ) O(logN) O(logN) 排序需要空间
哈希表

python实现

class Solution:
    def isAnagram(self, s: str, t: str) -> bool:
        if len(s) != len(t):
            return False
        
        counts = dict()
        for ch in s:
            if ch in counts:
                counts[ch] += 1
            else:
                counts[ch] = 1
        
        for ch in t:
            if ch in counts:
                counts[ch] -= 1
                if counts[ch] == 0:
                    del counts[ch]  # 删掉次数为0的key 
            else:
                return False
        
        return len(counts) == 0

c++实现

class Solution {
public:
    bool isAnagram(string s, string t) {
        if (s.size() != t.size())
            return false;
        
        unordered_map counts;

        for(char ch: s) {
            auto it = counts.find(ch);
            if (it != counts.end())
                counts[ch]++;
            else
                counts[ch] = 1;
        }

        for (char ch: t) {
            auto it = counts.find(ch);
            if (it == counts.end())
                return false;
            counts[ch]--;
            if (counts[ch] == 0)
                counts.erase(ch);
        }

        return counts.size() == 0;
    }
};

复杂度分析

  • 时间复杂度: O ( N ) O(N) O(N)
  • 空间复杂度: O ( S ) O(S) O(S) 字符的个数
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/983089.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号