跳到主要内容

819.最常见的单词

链接:819.最常见的单词
难度:Easy
标签:数组、哈希表、字符串、计数
简介:给定一个段落 (paragraph) 和一个禁用单词列表 (banned)。返回出现次数最多,同时不在禁用列表中的单词。

题解 1 - cpp

  • 编辑时间:2022-03-20
  • 执行用时:4ms
  • 内存消耗:7.4MB
  • 编程语言:cpp
  • 解法介绍:遍历。
class Solution {
public:
string mostCommonWord(string paragraph, vector<string>& banned) {
unordered_map<string, int> m;
unordered_set<string> s;
for (auto& ban : banned) s.insert(ban);
string ans = "";
int maxlen = 0, n = paragraph.size();
for (int i = 0; i < n; i++) {
while (i < n && !isalpha(paragraph[i])) i++;
if (i == n) break;
string tmp = "";
while (i < n && isalpha(paragraph[i]))
tmp += tolower(paragraph[i++]);
if (s.count(tmp)) continue;
m[tmp]++;
if (m[tmp] > maxlen) {
ans = tmp;
maxlen = m[tmp];
}
}
return ans;
}
};

题解 2 - cpp

  • 编辑时间:2022-04-17
  • 执行用时:4ms
  • 内存消耗:7.6MB
  • 编程语言:cpp
  • 解法介绍:遍历。
class Solution {
public:
string mostCommonWord(string paragraph, vector<string>& banned) {
int n = paragraph.size();
string ans = "";
unordered_map<string, int> m;
unordered_set<string> s;
for (auto& str : banned) s.insert(str);
for (int i = 0; i < n; i++) {
while (i < n && !isalpha(paragraph[i])) i++;
if (i == n) break;
int end = i;
string next = "";
do {
next += tolower(paragraph[end++]);
} while (end < n && isalpha(paragraph[end]));
if (!s.count(next) && m[ans] < ++m[next]) ans = next;
i = end;
}
return ans;
}
};