금지된 단어를 제외한 가장 흔하게 등장하는 단어를 출력하라.
대소문자 구분을 하지 않으며, 구두점 (마침표, 쉼표 등) 또한 무시한다.
Input: paragraph = "Bob hit a ball, the hit BALL flew far after it was hit.", banned = ["hit"]
Output: "ball"
Explanation:
"hit" occurs 3 times, but it is a banned word.
"ball" occurs twice (and no other word does), so it is the most frequent non-banned word in the paragraph.
Note that words in the paragraph are not case sensitive,
that punctuation is ignored (even if adjacent to words, such as "ball,"),
and that "hit" isn't the answer even though it occurs more because it is banned.
Input: paragraph = "a.", banned = []
Output: "a"
class Solution {
public:
string mostCommonWord(string paragraph, vector<string>& banned) {
string result;
multiset <string> ms;
int temp = 0;
int len = 0;
paragraph.append(" ");
int start = 0, end = 0;
for (int i = 0; i < paragraph.size(); i++)
{
paragraph[i] = tolower(paragraph[i]);
if (isalpha(paragraph[i]) == false)
{
end = i;
len = end - start;
string a = paragraph.substr(start, len);
if (isalpha(a[0]) != 0) ms.insert(a);
start = end + 1;
}
}
for (string a : banned) ms.erase(a);
multiset<string>::iterator iter;
int MaxCount = ms.count(*(ms.begin()));
for (iter = ms.begin(); iter != ms.end(); iter++)
{
if (MaxCount <= ms.count(*iter))
{
MaxCount = ms.count(*iter);
result = *iter;
}
}
return result;
}
};
multiset <string> ms;
paragraph.append(" ");
int start = 0, end = 0;
for (int i = 0; i < paragraph.size(); i++)
{
//1.
paragraph[i] = tolower(paragraph[i]);
//2.
if (isalpha(paragraph[i]) == false)
{
//3.
end = i;
len = end - start;
string a = paragraph.substr(start, len);
//4.
if (isalpha(a[0]) != 0) ms.insert(a);
start = end + 1;
}
}
for (string a : banned) ms.erase(a);
//1.
multiset<string>::iterator iter;
//2.
int MaxCount = ms.count(*(ms.begin()));
for (iter = ms.begin(); iter != ms.end(); iter++)
{
//3.
if (MaxCount <= ms.count(*iter))
{
MaxCount = ms.count(*iter);
result = *iter;
}
}
Runtime 13 ms / Memory 9.2 MB
https://leetcode.com/problems/most-common-word/submissions/879964026/