原题链接:819. 最常见的单词
solution:
class Solution {
public:
string lower(string str) { //将字符串转换为小写
for (int i = 0; i < str.size(); ++i)
str[i] = tolower(str[i]);
return str;
}
string mostCommonWord(string paragraph, vector<string>& banned) {
int n = paragraph.size();
int m = banned.size();
int res = 0;
string maxstr; //出现最大次数的单词
unordered_map<string,int> map1; //存储单词出现的次数
unordered_map<string,int> map2; //存储禁止出现的单词
for(auto &x : banned) map2[x]++;
for(int i = 0,j = 0;i < n && j < n;){
while(j < n && paragraph[j]!=' ' && isalpha(paragraph[j])) j++;
string str = lower(paragraph.substr(i,j - i));
if(!map2.count(str)){ //如果单词没有被禁用
map1[str]++;
if(res < map1[str]){
res = map1[str];
maxstr = str;
}
}
if(!isalpha(paragraph[j]) && paragraph[j] != ' ') j++; //去掉逗号等
while(j < n && !isalpha(paragraph[j])) j++; //去掉空格,将j移动到下一个单词开头
i = j; //i也移动
}
return maxstr;
}
};
//上面那个太麻烦重写了一次
class Solution {
public:
string mostCommonWord(string paragraph, vector<string>& banned) {
unordered_map<string,int> map1;
unordered_set<string> map2;
for(auto &x : banned) map2.insert(x); //插入
string word = "";
for(auto &y : paragraph){
y = tolower(y);
if (isalpha(y)) word += y;
else{
if(word.size()){
if(!map2.count(word)) map1[word]++;
word.clear();
}
}
}
if(word.size() && !map2.count(word)) map1[word]++;
//遍历哈希表
string res;
for(auto &[k,v] : map1){
if(map1[res] < v){
res = k;
}
}
return res;
}
};