【排序-简单】242. 有效的字母异位词

博客围绕判断两个字符串是否为字母异位词展开,给出示例及说明,假设字符串只含小写字母并提出进阶问题,即输入含unicode字符时解法的调整。同时给出Python和C++代码,展示了C++代码的执行用时和内存消耗情况。

【题目】
给定两个字符串 s 和 t ,编写一个函数来判断 t 是否是 s 的字母异位词。
【示例 1】
输入: s = “anagram”, t = “nagaram”
输出: true
【示例 2】
输入: s = “rat”, t = “car”
输出: false
【说明】
你可以假设字符串只包含小写字母。
【进阶】
如果输入字符串包含 unicode 字符怎么办?你能否调整你的解法来应对这种情况?
【代码】
【Python】
【方法1】

class Solution:
    def isAnagram(self, s: str, t: str) -> bool:
        s_dict,t_dict={},{}
        for c in s:
            if c not in s_dict:
                s_dict[c]=0
            s_dict[c]+=1
        for c in t:
            if c not in t_dict:
                t_dict[c]=0
            t_dict[c]+=1
        if len(s)!=len(t):
            return False
        for c in s_dict:
            print(c)
            if c not in t_dict:
                return False
            if t_dict[c]!=s_dict[c]:
                return False
        return True

【方法2】

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

【CPP】
执行用时:
4 ms, 在所有 C++ 提交中击败了98.19%的用户
内存消耗:
7.2 MB, 在所有 C++ 提交中击败了88.66%的用户

class Solution {
public:
    bool isAnagram(string s, string t) {
        int cnt[26]={0},cnt2[26]={0};
        for(auto x:s)
            cnt[x-'a']++;
        for(auto x:t)
            cnt2[x-'a']++;
        for(int i=0;i<26;i++)
            if(cnt2[i]!=cnt[i])
                return false;
        return true;
    }
};
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值