2025-04-24:举报垃圾信息。用go语言,给定两个字符串数组,message 和 bannedWords。
如果 message 中至少有两个单词,与 bannedWords 里的某个单词完全一致,那么 message 就被认为是垃圾信息。
如果 message 是垃圾信息,返回 true;否则返回 false。
1 <= message.length, bannedWords.length <= 100000。
1 <= message[i].length, bannedWords[i].length <= 15。
message[i] 和 bannedWords[i] 都只由小写英文字母组成。
输入: message = ["hello","world","leetcode"], bannedWords = ["world","hello"]。
输出: true。
解释:
数组 message 中的 "hello" 和 "world" 都出现在数组 bannedWords 中。
题目来自leetcode3295。
大体过程分步骤说明:
1.构建禁止单词集合:
• 遍历
bannedWords数组中的每一个单词。• 将这些单词存入一个哈希集合(如Go的
map[string]struct{})中。哈希集合的查询时间为O(1),可快速判断某个单词是否被禁止。
2.初始化计数器:
• 定义一个计数器
count,初始值为0,用于统计message中匹配的禁止单词数量。
3.遍历消息单词:
• 遍历
message数组中的每一个单词。• 对于每个单词,检查其是否存在于步骤1构建的哈希集合中:
•存在:计数器
count加1。此时立即检查计数器是否已达到2:• 若
count >= 2,立即返回true,无需继续遍历后续单词。
•不存在:跳过,继续检查下一个单词。
4.终止条件:
• 如果在遍历过程中,计数器达到2,直接返回
true。• 如果遍历完所有单词后,计数器仍小于2,则返回
false。
•时间复杂度:
• 构建哈希集合的时间为O(k),其中k是
bannedWords的长度。• 遍历
message的时间为O(m),其中m是message的长度。• 总时间复杂度为O(k + m)。
•空间复杂度:
• 哈希集合存储所有唯一的禁止单词,最坏情况下需要存储k个单词,因此空间复杂度为O(k)。
package main import ( "fmt" ) func reportSpam(message []string, bannedWords []string)bool { bannedSet := make(map[string]struct{}) for _, word := range bannedWords { bannedSet[word] = struct{}{} } count := 0 for _, word := range message { if _, exists := bannedSet[word]; exists { count++ if count >= 2 { returntrue } } } returnfalse } func main() { message := []string{"hello", "world", "leetcode"} bannedWords := []string{"world", "hello"} result := reportSpam(message, bannedWords) fmt.Println(result) }Python完整代码如下:
# -*-coding:utf-8-*- defreportSpam(message, bannedWords): banned_set = set(bannedWords) count = 0 for word in message: if word in banned_set: count += 1 if count >= 2: returnTrue returnFalse if __name__ == "__main__": message = ["hello", "world", "leetcode"] bannedWords = ["world", "hello"] result = reportSpam(message, bannedWords) print(result)我们相信 Go 语言和算法为普通开发者提供了强有力的“面试利器”,并致力于分享全面的编程知识。在这里,您可以找到最新的 Go 语言教程、算法解析、提升面试竞争力的秘籍以及行业动态。 欢迎关注“福大大架构师每日一题”,让 Go 语言和算法助力您的职业发展
特别声明:以上内容(如有图片或视频亦包括在内)为自媒体平台“网易号”用户上传并发布,本平台仅提供信息存储服务。
Notice: The content above (including the pictures and videos if any) is uploaded and posted by a user of NetEase Hao, which is a social media platform and only provides information storage services.