LeetCode 题解工作台

作为子字符串出现在单词中的字符串数目

给你一个字符串数组 patterns 和一个字符串 word ,统计 patterns 中有多少个字符串是 word 的子字符串。返回字符串数目。 子字符串 是字符串中的一个连续字符序列。 示例 1: 输入: patterns = ["a","abc","bc","d"], word = "abc"…

category

2

题型

code_blocks

6

代码语言

hub

3

相关题

当前训练重点

简单 · 数组·string

bolt

答案摘要

遍历字符串数组 中的每个字符串 ,判断其是否为 的子字符串,如果是,答案加一。 遍历结束后,返回答案。

Interview AiBox logo

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

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个字符串数组 patterns 和一个字符串 word ,统计 patterns 中有多少个字符串是 word 的子字符串。返回字符串数目。

子字符串 是字符串中的一个连续字符序列。

 

示例 1:

输入:patterns = ["a","abc","bc","d"], word = "abc"
输出:3
解释:
- "a" 是 "abc" 的子字符串。
- "abc" 是 "abc" 的子字符串。
- "bc" 是 "abc" 的子字符串。
- "d" 不是 "abc" 的子字符串。
patterns 中有 3 个字符串作为子字符串出现在 word 中。

示例 2:

输入:patterns = ["a","b","c"], word = "aaaaabbbbb"
输出:2
解释:
- "a" 是 "aaaaabbbbb" 的子字符串。
- "b" 是 "aaaaabbbbb" 的子字符串。
- "c" 不是 "aaaaabbbbb" 的字符串。
patterns 中有 2 个字符串作为子字符串出现在 word 中。

示例 3:

输入:patterns = ["a","a","a"], word = "ab"
输出:3
解释:patterns 中的每个字符串都作为子字符串出现在 word "ab" 中。

 

提示:

  • 1 <= patterns.length <= 100
  • 1 <= patterns[i].length <= 100
  • 1 <= word.length <= 100
  • patterns[i]word 由小写英文字母组成
lightbulb

解题思路

方法一:模拟

遍历字符串数组 patterns\textit{patterns} 中的每个字符串 pp,判断其是否为 word\textit{word} 的子字符串,如果是,答案加一。

遍历结束后,返回答案。

时间复杂度 O(n×m)O(n \times m),空间复杂度 O(1)O(1)。其中 nnmm 分别为 patterns\textit{patterns}word\textit{word} 的长度。

1
2
3
4
class Solution:
    def numOfStrings(self, patterns: List[str], word: str) -> int:
        return sum(p in word for p in patterns)
speed

复杂度分析

指标
时间Depends on the final approach
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    The candidate is expected to demonstrate an understanding of string matching techniques.

  • question_mark

    Evaluate if the candidate can handle edge cases where multiple identical patterns exist in the array.

  • question_mark

    Pay attention to how the candidate chooses their approach in terms of complexity and efficiency.

warning

常见陷阱

外企场景
  • error

    Failing to check for redundant patterns or using inefficient methods for substring matching.

  • error

    Not considering edge cases where patterns might be of the same string repeated or very similar.

  • error

    Overlooking the fact that every pattern should be checked individually without assuming overlap between patterns.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Test how the function handles an empty `patterns` array or an empty `word`.

  • arrow_right_alt

    Try larger `patterns` arrays or longer words to see if the solution scales appropriately.

  • arrow_right_alt

    Introduce mixed case inputs to assess how the candidate handles edge cases in substring checking.

help

常见问题

外企场景

作为子字符串出现在单词中的字符串数目题解:数组·string | LeetCode #1967 简单