comments | difficulty | edit_url | rating | source | tags | |||
---|---|---|---|---|---|---|---|---|
true |
中等 |
1198 |
第 416 场周赛 Q1 |
|
给你一个字符串数组 message
和一个字符串数组 bannedWords
。
如果数组中 至少 存在两个单词与 bannedWords
中的任一单词 完全相同,则该数组被视为 垃圾信息。
如果数组 message
是垃圾信息,则返回 true
;否则返回 false
。
示例 1:
输入: message = ["hello","world","leetcode"], bannedWords = ["world","hello"]
输出: true
解释:
数组 message
中的 "hello"
和 "world"
都出现在数组 bannedWords
中。
示例 2:
输入: message = ["hello","programming","fun"], bannedWords = ["world","programming","leetcode"]
输出: false
解释:
数组 message
中只有一个单词("programming"
)出现在数组 bannedWords
中。
提示:
1 <= message.length, bannedWords.length <= 105
1 <= message[i].length, bannedWords[i].length <= 15
message[i]
和bannedWords[i]
都只由小写英文字母组成。
我们用一个哈希表
时间复杂度
class Solution:
def reportSpam(self, message: List[str], bannedWords: List[str]) -> bool:
s = set(bannedWords)
return sum(w in s for w in message) >= 2
class Solution {
public boolean reportSpam(String[] message, String[] bannedWords) {
Set<String> s = new HashSet<>();
for (var w : bannedWords) {
s.add(w);
}
int cnt = 0;
for (var w : message) {
if (s.contains(w) && ++cnt >= 2) {
return true;
}
}
return false;
}
}
class Solution {
public:
bool reportSpam(vector<string>& message, vector<string>& bannedWords) {
unordered_set<string> s(bannedWords.begin(), bannedWords.end());
int cnt = 0;
for (const auto& w : message) {
if (s.contains(w) && ++cnt >= 2) {
return true;
}
}
return false;
}
};
func reportSpam(message []string, bannedWords []string) bool {
s := map[string]bool{}
for _, w := range bannedWords {
s[w] = true
}
cnt := 0
for _, w := range message {
if s[w] {
cnt++
if cnt >= 2 {
return true
}
}
}
return false
}
function reportSpam(message: string[], bannedWords: string[]): boolean {
const s = new Set<string>(bannedWords);
let cnt = 0;
for (const w of message) {
if (s.has(w) && ++cnt >= 2) {
return true;
}
}
return false;
}