字母的异位数

做leetcode242题时出现了一个错误:

bool isAnagram(string s, string t) {
        map<char,int> cnt;
        bool ans = true;
        int lens = s.length();
        int lent = t.length();
        for(int i = 0;i < lens;i++){
            cnt[s[i]] += 1;
            cout << cnt[s[i]] << endl;
        }
        for(int i = 0;i < lent;i++){
            if(cnt[t[i]] == 0){
                cout << t[i] << cnt[t[i]] << endl;
                ans = false;
                break;
            }else{
                cnt[t[i]] -= 1;
            }
        }

        // if(!cnt.empty()){
        //     cout << "here" << endl;
        //     ans = false;
        // }
        for(auto& kv:cnt){
            if(kv.second != 0){
                ans = false;
                break;
            }
        }

其中判断map是否为空我使用

if(!cnt.empty()){
             cout << "here" << endl;
             ans = false;
        }

isAnagram 函数的主要问题在于检查 cnt 是否为空的方式。即使在字符串 t 中的字符与 s 完全匹配,cnt 也不会自动变为空,而是会包含值为零的字符计数。即当map里的数全都归零时,map也非空,而是字母和0的映射,因此不能用cnt.empty()判断,而是选用

for(auto& kv:cnt){
            if(kv.second != 0){
                ans = false;
                break;
            }
        }

来判断map内部是否都是0;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Andrew_Chao

谢谢打赏喵

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值