LeetCode 题解工作台

统计包含给定前缀的字符串

给你一个字符串数组 words 和一个字符串 pref 。 返回 words 中以 pref 作为 前缀 的字符串的数目。 字符串 s 的 前缀 就是 s 的任一前导连续字符串。 示例 1: 输入: words = ["pay"," at tention","practice"," at tend"…

category

3

题型

code_blocks

7

代码语言

hub

3

相关题

当前训练重点

简单 · 数组·string

bolt

答案摘要

根据题目描述,我们遍历字符串数组 `words` 中的每个字符串 ,判断其是否以 作为前缀,如果是,则答案加一。 时间复杂度 $O(n \times m)$,空间复杂度 。其中 和 分别是字符串数组 `words` 和字符串 的长度。

Interview AiBox logo

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

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个字符串数组 words 和一个字符串 pref

返回 words 中以 pref 作为 前缀 的字符串的数目。

字符串 s前缀 就是  s 的任一前导连续字符串。

 

示例 1:

输入:words = ["pay","attention","practice","attend"], pref = "at"
输出:2
解释:以 "at" 作为前缀的字符串有两个,分别是:"attention" 和 "attend" 。

示例 2:

输入:words = ["leetcode","win","loops","success"], pref = "code"
输出:0
解释:不存在以 "code" 作为前缀的字符串。

 

提示:

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

解题思路

方法一:一次遍历

根据题目描述,我们遍历字符串数组 words 中的每个字符串 ww,判断其是否以 prefpref 作为前缀,如果是,则答案加一。

时间复杂度 O(n×m)O(n \times m),空间复杂度 O(1)O(1)。其中 nnmm 分别是字符串数组 words 和字符串 prefpref 的长度。

1
2
3
4
class Solution:
    def prefixCount(self, words: List[str], pref: str) -> int:
        return sum(w.startswith(pref) for w in words)
speed

复杂度分析

指标
时间O(n \cdot l + m)
空间O(n \cdot l)
psychology

面试官常问的追问

外企场景
  • question_mark

    Check if the candidate can efficiently iterate over a list and perform string matching.

  • question_mark

    Assess if the candidate considers edge cases like empty strings or no matches.

  • question_mark

    Evaluate whether the candidate optimizes string matching appropriately for large inputs.

warning

常见陷阱

外企场景
  • error

    Failing to handle the case where the prefix is longer than the word.

  • error

    Not considering the empty string as a valid prefix.

  • error

    Inefficiently checking each character of the string when more efficient methods like startsWith() exist.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    What if the prefix is empty?

  • arrow_right_alt

    What if words contain varying lengths?

  • arrow_right_alt

    Can the solution be optimized for larger arrays of words?

help

常见问题

外企场景

统计包含给定前缀的字符串题解:数组·string | LeetCode #2185 简单