LeetCode 题解工作台

统计是给定字符串前缀的字符串数目

给你一个字符串数组 words 和一个字符串 s ,其中 words[i] 和 s 只包含 小写英文字母 。 请你返回 words 中是字符串 s 前缀 的 字符串数目 。 一个字符串的 前缀 是出现在字符串开头的子字符串。 子字符串 是一个字符串中的连续一段字符序列。 示例 1: 输入: word…

category

2

题型

code_blocks

7

代码语言

hub

3

相关题

当前训练重点

简单 · 数组·string

bolt

答案摘要

我们直接遍历数组 ,对于每个字符串 ,判断 是否以 为前缀,如果是则答案加一。 遍历结束后,返回答案即可。

Interview AiBox logo

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

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个字符串数组 words 和一个字符串 s ,其中 words[i] 和 s 只包含 小写英文字母 。

请你返回 words 中是字符串 s 前缀 字符串数目 。

一个字符串的 前缀 是出现在字符串开头的子字符串。子字符串 是一个字符串中的连续一段字符序列。

 

示例 1:

输入:words = ["a","b","c","ab","bc","abc"], s = "abc"
输出:3
解释:
words 中是 s = "abc" 前缀的字符串为:
"a" ,"ab" 和 "abc" 。
所以 words 中是字符串 s 前缀的字符串数目为 3 。

示例 2:

输入:words = ["a","a"], s = "aa"
输出:2
解释:
两个字符串都是 s 的前缀。
注意,相同的字符串可能在 words 中出现多次,它们应该被计数多次。

 

提示:

  • 1 <= words.length <= 1000
  • 1 <= words[i].length, s.length <= 10
  • words[i] 和 s  包含小写英文字母。
lightbulb

解题思路

方法一:遍历计数

我们直接遍历数组 words\textit{words},对于每个字符串 ww,判断 ss 是否以 ww 为前缀,如果是则答案加一。

遍历结束后,返回答案即可。

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

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

复杂度分析

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

面试官常问的追问

外企场景
  • question_mark

    The candidate is expected to demonstrate familiarity with string manipulation techniques.

  • question_mark

    Efficiency in handling edge cases such as duplicate words should be discussed.

  • question_mark

    Candidates may be expected to propose optimizations or alternative solutions for larger input sizes.

warning

常见陷阱

外企场景
  • error

    Forgetting to count duplicate words in the list.

  • error

    Overcomplicating the solution by using complex algorithms for a simple problem.

  • error

    Neglecting to account for edge cases such as an empty list or a word being exactly the same as `s`.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Instead of using the `startswith` method, implement a manual comparison of the beginning substring.

  • arrow_right_alt

    Consider a case where the list of words is very large, and explore optimized approaches like sorting or hashing.

  • arrow_right_alt

    Extend the problem to check for prefixes of multiple target strings, not just one.

help

常见问题

外企场景

统计是给定字符串前缀的字符串数目题解:数组·string | LeetCode #2255 简单