LeetCode 题解工作台
单词拆分
给你一个字符串 s 和一个字符串列表 wordDict 作为字典。如果可以利用字典中出现的一个或多个单词拼接出 s 则返回 true 。 注意: 不要求字典中出现的单词全部都使用,并且字典中的单词可以重复使用。 示例 1: 输入: s = "leetcode", wordDict = ["leet"…
6
题型
7
代码语言
3
相关题
当前训练重点
中等 · 数组·哈希·扫描
答案摘要
我们定义 表示字符串 的前 个字符能否拆分成 中的单词,初始时 ,其余为 。答案为 。 考虑 ,如果存在 $j \in [0, i)$ 使得 $f[j] \land s[j:i] \in wordDict$,则 。为了优化效率,我们可以使用哈希表存储 中的单词,这样可以快速判断 是否在 中。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·哈希·扫描 题型思路
题目描述
给你一个字符串 s 和一个字符串列表 wordDict 作为字典。如果可以利用字典中出现的一个或多个单词拼接出 s 则返回 true。
注意:不要求字典中出现的单词全部都使用,并且字典中的单词可以重复使用。
示例 1:
输入: s = "leetcode", wordDict = ["leet", "code"] 输出: true 解释: 返回 true 因为 "leetcode" 可以由 "leet" 和 "code" 拼接成。
示例 2:
输入: s = "applepenapple", wordDict = ["apple", "pen"] 输出: true 解释: 返回 true 因为 "applepenapple" 可以由 "apple" "pen" "apple" 拼接成。 注意,你可以重复使用字典中的单词。
示例 3:
输入: s = "catsandog", wordDict = ["cats", "dog", "sand", "and", "cat"] 输出: false
提示:
1 <= s.length <= 3001 <= wordDict.length <= 10001 <= wordDict[i].length <= 20s和wordDict[i]仅由小写英文字母组成wordDict中的所有字符串 互不相同
解题思路
方法一:哈希表 + 动态规划
我们定义 表示字符串 的前 个字符能否拆分成 中的单词,初始时 ,其余为 。答案为 。
考虑 ,如果存在 使得 ,则 。为了优化效率,我们可以使用哈希表存储 中的单词,这样可以快速判断 是否在 中。
时间复杂度 ,空间复杂度 。其中 为字符串 的长度。
class Solution:
def wordBreak(self, s: str, wordDict: List[str]) -> bool:
words = set(wordDict)
n = len(s)
f = [True] + [False] * n
for i in range(1, n + 1):
f[i] = any(f[j] and s[j:i] in words for j in range(i))
return f[n]
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | O(n^3 + m \cdot k) |
| 空间 | O(n + m \cdot k) |
面试官常问的追问
外企场景- question_mark
Do you recognize the overlapping subproblem structure in this string segmentation scenario?
- question_mark
Can you optimize substring lookups to avoid repeated dictionary searches using hash sets or tries?
- question_mark
Will you explain how DP or memoization prevents redundant scanning of overlapping string segments?
常见陷阱
外企场景- error
Forgetting that dictionary words can be reused multiple times, leading to false negatives in segmentation.
- error
Checking all substrings inefficiently without leveraging DP or memoization, causing timeouts.
- error
Using a list search instead of a hash set, which increases lookup time from O(1) to O(m) per substring.
进阶变体
外企场景- arrow_right_alt
Word Break II: Return all possible segmentations of s instead of a boolean, exploring recursion with memoization.
- arrow_right_alt
Word Break with Limited Reuse: Each word can be used only a fixed number of times, requiring additional tracking per word.
- arrow_right_alt
Word Break III: Count the number of valid segmentations instead of returning a boolean, focusing on DP sum accumulation.