题目链接:
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