819. 最常见的单词
哈希+计数
把段落中每个单词拿出来,看是否在禁用词中即可。熟练使用tolower、toupper、isalpha
本题会更加有助于解题。
class Solution
{
public:
bool is_char(char s)
{
if (s >= 'a' && s <= 'z')
return true;
if (s >= 'A' && s <= 'Z')
return true;
return false;
}
string mostCommonWord(string paragraph, vector<string> &banned)
{
set<string> S;
for (auto &s : banned)
S.insert(s);
map<string, int> mp;
string word;
for (int i = 0; i < paragraph.size(); i++)
{
int j = i;
if (!is_char(paragraph[j]))
continue;
while (j < paragraph.size() && is_char(paragraph[j]))
word += tolower(paragraph[j++]);
mp[word]++;
i = j - 1;
word = "";
}
string res;
int maxn = 0;
for (auto &[u, v] : mp)
if (!S.count(u) && v > maxn)
{
res = u;
maxn = v;
}
return res;
}
};