LeetCode 题解工作台

数组中的字符串匹配

给你一个字符串数组 words ,数组中的每个字符串都可以看作是一个单词。请你按 任意 顺序返回 words 中是其他单词的 子字符串 的所有单词。 示例 1: 输入: words = ["mass","as","hero","superhero"] 输出: ["as","hero"] 解释: "a…

category

3

题型

code_blocks

6

代码语言

hub

3

相关题

当前训练重点

简单 · 数组·string

bolt

答案摘要

我们直接枚举所有的字符串 ,判断其是否为其他字符串的子串,如果是,将其加入答案。 时间复杂度 ,空间复杂度 。其中 为字符串数组的长度。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 数组·string 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个字符串数组 words ,数组中的每个字符串都可以看作是一个单词。请你按 任意 顺序返回 words 中是其他单词的 子字符串 的所有单词。

 

示例 1:

输入:words = ["mass","as","hero","superhero"]
输出:["as","hero"]
解释:"as" 是 "mass" 的子字符串,"hero" 是 "superhero" 的子字符串。
["hero","as"] 也是有效的答案。

示例 2:

输入:words = ["leetcode","et","code"]
输出:["et","code"]
解释:"et" 和 "code" 都是 "leetcode" 的子字符串。

示例 3:

输入:words = ["blue","green","bu"]
输出:[]

 

提示:

  • 1 <= words.length <= 100
  • 1 <= words[i].length <= 30
  • words[i] 仅包含小写英文字母。
  • 题目数据 保证 words 的每个字符串都是独一无二的。
lightbulb

解题思路

方法一:暴力枚举

我们直接枚举所有的字符串 words[i]words[i],判断其是否为其他字符串的子串,如果是,将其加入答案。

时间复杂度 O(n3)O(n^3),空间复杂度 O(n)O(n)。其中 nn 为字符串数组的长度。

1
2
3
4
5
6
7
8
class Solution:
    def stringMatching(self, words: List[str]) -> List[str]:
        ans = []
        for i, s in enumerate(words):
            if any(i != j and s in t for j, t in enumerate(words)):
                ans.append(s)
        return ans
speed

复杂度分析

指标
时间complexity is O(m^2 \times n) because each of the m strings is compared with every other string, and each comparison may scan up to n characters. Space complexity is O(m^2 \times n) when storing substring results, especially if using sets to avoid duplicates.
空间O(m^2 \times n)
psychology

面试官常问的追问

外企场景
  • question_mark

    Check if candidates attempt naive pairwise comparisons or optimize using sorting by length.

  • question_mark

    Observe if candidates consider substring edge cases like identical or nested substrings.

  • question_mark

    Listen for discussion on using string search algorithms such as KMP to improve efficiency.

warning

常见陷阱

外企场景
  • error

    Failing to account for all pairs, missing substrings contained in multiple words.

  • error

    Returning duplicates if using lists instead of sets for results.

  • error

    Ignoring constraints and attempting unnecessary optimizations for small arrays.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Return substrings that appear in at least k other strings instead of just one.

  • arrow_right_alt

    Count the total number of substring occurrences across all words instead of returning the words.

  • arrow_right_alt

    Find substrings that are both prefixes and suffixes of other words, combining array plus string logic.

help

常见问题

外企场景

数组中的字符串匹配题解:数组·string | LeetCode #1408 简单