[leetcode oj 242]Valid Anagram

本文介绍了一种判断两个字符串是否互为异位词的方法。通过比较两个字符串的长度,利用计数数组来统计每个字符出现的次数,最终确定它们是否由相同的字符组成。

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

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.

呼哈哈哈哈。。。毫无思路。。。本来是想呢。。。遇到一个字母就统计次数。。。复杂性是不是太高。。。
然后又想了,顺序读s中的字符,如果在t中找到,则s和t的对应位同时清零,最后只要看看是不是都是清空了就好了,机智如我。

class Solution {
public:
    bool isAnagram(string s, string t) {
        int count = 0;
        if(s.length() != t.length())
            return false;
        for(int i = 0;i < s.length();i++)
        {
            for(int j = 0;j < t.length();j++)
            {
                if(s[i] == t[j])
                {
                    s[i] = ' ';
                    t[j] = ' ';
                    count++;
                }
            }
        }
        if(count == s.length())
            return true;
        return false;
    }
};

然后就。。。华丽丽的超时了。。。
后来发现。。。原来题里说你可以假设只有小写。。。噗。。。一口老血。。。那么就是说。。。开一个count[26],s出现的count++,t出现的count–,最后如果count都是0,那么就ok了。

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

that’s it

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值