leetcode:242. Valid Anagram

博客提及统计字母出现次数,认为自己想法天真,看到大神做法觉得很巧妙,还提到追求极限可能要用map等方法。

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

想法太天真了点:

错误,容我想想,

class Solution {
public:
    bool isAnagram(string s, string t) {
     
        int len=s.length();
        int len_t=t.length();
        if(len!=len_t)return false;
        int res=0;
        for(auto i=0;i<len;i++)
        {
            res+=s[i]-t[i];
            printf("%d\n",res);
        }
        return res==0 ? true:false;
    }
};

 

统计字母出现次数,

/*
思路:
统计每个字母出现的次数,
*/

// class Solution {
// public:
//     bool isAnagram(string s, string t) {
     
//         int len=s.length();
//         int len_t=t.length();
//         if(len!=len_t)return false;
//         int res=0;
//         for(auto i=0;i<len;i++)
//         {
//             res+=s[i]-t[i];
//             printf("%d\n",res);
//         }
//         return res==0 ? true:false;
//     }
// };


/*
思路:
统计每个字母出现的次数,形成map,如果直接用map要怎么做呢
*/


class Solution {
public:
    bool isAnagram(string s, string t) {
     
        int len_s=s.length(),len_t=t.length();
        if(len_s!=len_t)return false;

        int count_s[256]={0},count_t[256]={0};
        
        for(auto i=0;i<len_s;i++)
        {//map to arry
            count_s[s[i]]++;
            count_t[t[i]]++;
        }
        for(auto i=0;i<256;i++)
        {//judge if 2 arry equal
            if(count_s[i]!=count_t[i])
                return false;
        }
        return true;
    }
};

 

看看人家大神的,挺巧妙:

追求极限,

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

 

估计要用map那些好

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值