【一天一道LeetCode】#242. Valid Anagram

本文介绍了一道LeetCode上的经典字符串题目的两种解法,一种是通过排序比较,另一种是利用哈希表计数的方式,后者效率更高。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一天一道LeetCode

本系列文章已全部上传至我的github,地址:ZeeCoder‘s Github
欢迎大家关注我的新浪微博,我的新浪微博
欢迎转载,转载请注明出处

(一)题目

Given two strings s and t, write a function to determine if t is an anagram of s.

For example,
s = “anagram”, t = “nagaram”, return true.
s = “rat”, t = “car”, return false.

Note:
You may assume the string contains only lowercase alphabets.

Follow up:
What if the inputs contain unicode characters? How would you adapt your solution to such case?

(二)解题

题目大意:给定两个字符串s和t,判断t是不是s的有效字谜

解题思路:有效字谜是指t是由s中的字符改变相对位置后组成的字符串。

84ms解题版本:

class Solution {
public:
    bool isAnagram(string s, string t) {
        if(s.length()!=t.length()) return false;//长度不等,直接返回false
        sort(s.begin(),s.end());//排序
        sort(t.begin(),t.end());
        return s==t?true:false;//判断是否相等
    }
};

12ms的版本:

用哈希表,首先遍历s,记录每个字符出现的次数,然后遍历t,出现某个字符就次数就减1,判断最后的次数是否都为0

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值