2025-04-24:举报垃圾信息。用go语言,给定两个字符串数组,message 和 bannedWords。 如果 message 中至少有两个单词,与 b

20 阅读2分钟

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)

Go完整代码如下:

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 {
				return true
			}
		}
	}
	return false
}

func main() {
	message := []string{"hello", "world", "leetcode"}
	bannedWords := []string{"world", "hello"}
	result := reportSpam(message, bannedWords)
	fmt.Println(result)
}

在这里插入图片描述

Python完整代码如下:

# -*-coding:utf-8-*-

def reportSpam(message, bannedWords):
    banned_set = set(bannedWords)
    count = 0
    for word in message:
        if word in banned_set:
            count += 1
            if count >= 2:
                return True
    return False

if __name__ == "__main__":
    message = ["hello", "world", "leetcode"]
    bannedWords = ["world", "hello"]
    result = reportSpam(message, bannedWords)
    print(result)

在这里插入图片描述