Every day a Leetcode
题目来源:3295. 举报垃圾信息
解法1:哈希
将字符串数组 bannedWords 的字符串保存在一个哈希表里。
遍历字符串数组 message 的每一个字符串 mes,如果 mes 在哈希表中出现,count++。
如果 count >= 2,说明数组 message 是垃圾信息,则返回 true;否则返回 false。
代码:
/*
* @lc app=leetcode.cn id=3295 lang=cpp
*
* [3295] 举报垃圾信息
*/
// @lc code=start
class Solution
{
public:
bool reportSpam(vector<string> &message, vector<string> &bannedWords)
{
unordered_set<string> hashSet(bannedWords.begin(), bannedWords.end());
int count = 0;
for (string &mes : message)
if (hashSet.contains(mes))
count++;
return count >= 2;
}
};
// @lc code=end
结果:

复杂度分析:
时间复杂度:O((n+m) * l),其中 n 是数组 message 的长度,m 是数组 bannedWords 的长度,l≤15 是字符串的最大长度。
空间复杂度:O(m * l),其中 m 是数组 bannedWords 的长度,l≤15 是字符串的最大长度。
239

被折叠的 条评论
为什么被折叠?



