LeetCode 题解工作台

检查字符串是否为数组前缀

给你一个字符串 s 和一个字符串数组 words ,请你判断 s 是否为 words 的 前缀字符串 。 字符串 s 要成为 words 的 前缀字符串 ,需要满足: s 可以由 words 中的前 k ( k 为 正数 )个字符串按顺序相连得到,且 k 不超过 words.length 。 如果 …

category

3

题型

code_blocks

5

代码语言

hub

3

相关题

当前训练重点

简单 · 双·指针·invariant

bolt

答案摘要

我们遍历数组 ,用一个变量 记录当前已经拼接的字符串,如果 的长度大于 的长度,说明 不是 的前缀字符串,返回 ;如果 的长度等于 的长度,返回 是否等于 。 遍历结束后,如果 的长度小于 的长度,说明 不是 的前缀字符串,返回 。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 双·指针·invariant 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个字符串 s 和一个字符串数组 words ,请你判断 s 是否为 words前缀字符串

字符串 s 要成为 words前缀字符串 ,需要满足:s 可以由 words 中的前 kk正数 )个字符串按顺序相连得到,且 k 不超过 words.length

如果 swords前缀字符串 ,返回 true ;否则,返回 false

 

示例 1:

输入:s = "iloveleetcode", words = ["i","love","leetcode","apples"]
输出:true
解释:
s 可以由 "i"、"love" 和 "leetcode" 相连得到。

示例 2:

输入:s = "iloveleetcode", words = ["apples","i","love","leetcode"]
输出:false
解释:
数组的前缀相连无法得到 s 。

 

提示:

  • 1 <= words.length <= 100
  • 1 <= words[i].length <= 20
  • 1 <= s.length <= 1000
  • words[i]s 仅由小写英文字母组成
lightbulb

解题思路

方法一:遍历

我们遍历数组 wordswords,用一个变量 tt 记录当前已经拼接的字符串,如果 tt 的长度大于 ss 的长度,说明 ss 不是 wordswords 的前缀字符串,返回 falsefalse;如果 tt 的长度等于 ss 的长度,返回 tt 是否等于 ss

遍历结束后,如果 tt 的长度小于 ss 的长度,说明 ss 不是 wordswords 的前缀字符串,返回 falsefalse

时间复杂度 O(n)O(n),空间复杂度 O(n)O(n)。其中 nn 是字符串 ss 的长度。

1
2
3
4
5
6
7
8
9
class Solution:
    def isPrefixString(self, s: str, words: List[str]) -> bool:
        n, m = len(s), 0
        for i, w in enumerate(words):
            m += len(w)
            if m == n:
                return "".join(words[: i + 1]) == s
        return False
speed

复杂度分析

指标
时间complexity is O(L) where L is the sum of lengths of the words used in the prefix, as we scan each character once. Space complexity is O(1) extra space if concatenation is done incrementally without building a full string.
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    Checking two-pointer alignment between s and words array.

  • question_mark

    Observing early exit opportunities when prefix lengths mismatch.

  • question_mark

    Identifying incremental concatenation versus full array join.

warning

常见陷阱

外企场景
  • error

    Attempting to join all words before comparing, which wastes memory and time.

  • error

    Ignoring partial matches and scanning beyond necessary prefix length.

  • error

    Mismanaging pointer increments when word boundaries are crossed.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Instead of string s, check if a sequence of numbers is a prefix of an array of arrays.

  • arrow_right_alt

    Allow s to match any subsequence of words rather than just a prefix.

  • arrow_right_alt

    Check prefix matching ignoring case sensitivity or including delimiters.

help

常见问题

外企场景

检查字符串是否为数组前缀题解:双·指针·invariant | LeetCode #1961 简单