leetcode 290有感—永远不要比较无符号数与有符号数

题目链接:

https://leetcode.com/problems/word-pattern/


一开始wrong answer的做法:

class Solution {
public:
    bool wordPattern(string pattern, string str) {
        unordered_map<char, string> a;
        unordered_map<string, char> b;
        int indexStr=-1;
        for (int i=0; i<pattern.size(); ++i) {
            ++indexStr;
            string add;
            while (indexStr<str.size() && str[indexStr]!=' ') {
                add.push_back(str[indexStr++]);
            }
            if (add.empty()) return false;
            if (a[pattern[i]]=="" && b[add]==0) {
                a[pattern[i]]=add;
                b[add]=pattern[i];
            }else{
                if (a[pattern[i]]!=add || b[add]!=pattern[i]) {
                    return false;
                }
            }
        }
        if (indexStr<str.size()) return false;
        return true;
    }
};

后来AC了:

class Solution {
public:
    bool wordPattern(string pattern, string str) {
        map<char, string> a;
        map<string, char> b;
        int indexStr=-1;
        for (int i=0; i<pattern.size(); ++i) {
            ++indexStr;
            string add;
            while (indexStr<str.size() && str[indexStr]!=' ') {
                add.push_back(str[indexStr++]);
            }
            if (add.empty()) return false;
            if (a[pattern[i]]=="" && b[add]==0) {
                a[pattern[i]]=add;
                b[add]=pattern[i];
            }else{
                if (a[pattern[i]]!=add || b[add]!=pattern[i]) {
                    return false;
                }
            }
        }
        // 修改了这里
        if (indexStr<(int)str.size()) return false;
        
        return true;
    }
};

原因:

// 永远不要让一个无符号数与有符号数进行比较
// 进行比较时,有符号数会自动转换成无符号数
// 例如,-1会转换为2^31-1


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值