LeetCode 题解工作台
检查字符串是否为数组前缀
给你一个字符串 s 和一个字符串数组 words ,请你判断 s 是否为 words 的 前缀字符串 。 字符串 s 要成为 words 的 前缀字符串 ,需要满足: s 可以由 words 中的前 k ( k 为 正数 )个字符串按顺序相连得到,且 k 不超过 words.length 。 如果 …
3
题型
5
代码语言
3
相关题
当前训练重点
简单 · 双·指针·invariant
答案摘要
我们遍历数组 ,用一个变量 记录当前已经拼接的字符串,如果 的长度大于 的长度,说明 不是 的前缀字符串,返回 ;如果 的长度等于 的长度,返回 是否等于 。 遍历结束后,如果 的长度小于 的长度,说明 不是 的前缀字符串,返回 。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 双·指针·invariant 题型思路
题目描述
给你一个字符串 s 和一个字符串数组 words ,请你判断 s 是否为 words 的 前缀字符串 。
字符串 s 要成为 words 的 前缀字符串 ,需要满足:s 可以由 words 中的前 k(k 为 正数 )个字符串按顺序相连得到,且 k 不超过 words.length 。
如果 s 是 words 的 前缀字符串 ,返回 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 <= 1001 <= words[i].length <= 201 <= s.length <= 1000words[i]和s仅由小写英文字母组成
解题思路
方法一:遍历
我们遍历数组 ,用一个变量 记录当前已经拼接的字符串,如果 的长度大于 的长度,说明 不是 的前缀字符串,返回 ;如果 的长度等于 的长度,返回 是否等于 。
遍历结束后,如果 的长度小于 的长度,说明 不是 的前缀字符串,返回 。
时间复杂度 ,空间复杂度 。其中 是字符串 的长度。
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
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | 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 |
面试官常问的追问
外企场景- 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.
常见陷阱
外企场景- 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.
进阶变体
外企场景- 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.