Given a paragraph and a list of banned words, return the most frequent word that is not in the list of banned words. It is guaranteed there is at least one word that isn’t banned, and that the answer is unique.
Words in the list of banned words are given in lowercase, and free of punctuation. Words in the paragraph are not case sensitive. The answer is in lowercase.
Example:
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.
Note:
- 1 <= paragraph.length <= 1000.
- 0 <= banned.length <= 100.
- 1 <= banned[i].length <= 10.
- The answer is unique, and written in lowercase (even if its occurrences in paragraph may have uppercase symbols, and even if it is a proper noun.)
paragraph only consists of letters, spaces, or the punctuation symbols !?’,;. - There are no hyphens or hyphenated words.
- Words only consist of letters, never apostrophes or other punctuation symbols.
方法1: hash
discussion: https://leetcode.com/problems/most-common-word/discuss/123822/C%2B%2B-Simple-Solution
思路:
是一道string 的实现题。1. 用hash 把banned存起来O(1)查找,去掉所有的punctuation。这里由于没有给清所有punctuation可能的情况是什么,如果去掉了是否能保证单词独立,比如school’s, 或者word:word所以保险起见是先遍历一边都换成‘ ’,然后用stream parse。
易错点:
- 注意getline和istringstream >> tmp的使用区别:getline是无法deal with 连续空格或其他deliminator的,会在连续分隔符之间返回“”(空字符串)。而istringstream可以,内部实现是string buffer。
class Solution {
public:
string mostCommonWord(string paragraph, vector<string>& banned) {
unordered_set<string> ban(begin(banned), end(banned));
unordered_map<string, int> hash;
for (auto & c: paragraph) {
if (!isalpha(c)) c = ' ';
else c = tolower(c);
}
istringstream in(paragraph);
string tmp, res;
int mx = 0;
while (in >> tmp) {
if (ban.count(tmp)) continue;
if (++hash[tmp] > mx) {
res = tmp;
mx = hash[tmp];
}
}
return res;
}
};
下面这种写法值得注意,用remove_it的方式可以将所有指定的deliminator去掉,实现的方式是stable partition。也就是说,对于指定的function,返回true的值都被删掉(换到后面),false的留下,而返回值是最后一个false值的下一个iterator,想要得到truncated还要调用一次erase。虽然这道题里不能使用,因为去掉之后单词不独立,但用法可以记住。
class Solution {
public:
string mostCommonWord(string paragraph, vector<string>& banned) {
unordered_set<string> ban(begin(banned), end(banned));
unordered_map<string, int> hash;
unordered_set<char> punc = {',', '.', '?', '!', '\'', ';'};
auto is_punc = [&punc](char c) { return punc.count (c); };
paragraph.erase(remove_if(begin(paragraph), end(paragraph), is_punc), paragraph.end());
for (auto& c : paragraph) c = tolower (c);
istringstream in(paragraph);
string tmp, res;
int mx = 0;
while (in >> tmp) {
if (ban.count(tmp)) continue;
if (++hash[tmp] > mx) {
res = tmp;
mx = hash[tmp];
}
}
return res;
}
};