Input: message =["hello","world","leetcode"], bannedWords =["world","hello"]Output: trueExplanation:
The words `"hello"` and `"world"` from the `message` array both appear in the
`bannedWords` array.
Input: message =["hello","programming","fun"], bannedWords =["world","programming","leetcode"]Output: falseExplanation:
Only one word from the `message` array (`"programming"`) appears in the
`bannedWords` array.
We want to quickly check how many words in the message are present in the bannedWords list. If at least two such words exist, the message is spam. Using a set for bannedWords allows O(1) lookup per word.
import java.util.*;
publicclassSolution {
publicbooleanisSpamMessage(String[] message, String[] bannedWords) {
Set<String> banned =new HashSet<>(Arrays.asList(bannedWords));
int count = 0;
for (String word : message) {
if (banned.contains(word)) {
count++;
if (count == 2) returntrue;
}
}
returnfalse;
}
}
1
2
3
4
5
6
7
8
9
10
11
funisSpamMessage(message: Array<String>, bannedWords: Array<String>): Boolean {
val banned = bannedWords.toSet()
var count = 0for (word in message) {
if (word in banned) {
count++if (count ==2) returntrue }
}
returnfalse}
1
2
3
4
5
6
7
8
9
defisSpamMessage(message, bannedWords):
banned = set(bannedWords)
count =0for word in message:
if word in banned:
count +=1if count ==2:
returnTruereturnFalse
1
2
3
4
5
6
7
8
9
10
11
12
13
14
use std::collections::HashSet;
fnis_spam_message(message: &[String], banned_words: &[String]) -> bool {
let banned: HashSet<_>= banned_words.iter().collect();
letmut count =0;
for word in message {
if banned.contains(word) {
count +=1;
if count ==2 {
returntrue;
}
}
}
false}
1
2
3
4
5
6
7
8
9
10
11
functionisSpamMessage(message: string[], bannedWords: string[]):boolean {
constbanned=newSet(bannedWords);
letcount=0;
for (constwordofmessage) {
if (banned.has(word)) {
count++;
if (count===2) returntrue;
}
}
returnfalse;
}