class Solution:
def wordBreak(self, s: str, wordDict: List[str]) -> bool:
dp=[False]*(len(s)+1)
dp[0]=True
for i in range(len(s)+1):
for word in wordDict:
if dp[i] and (i+len(word))<=len(s) and word ==s[i:i+len(word)]:
dp[i+len(word)]=True
return dp[-1]
class Solution:
def wordBreak0(self, s: str, wordDict: List[str]) -> bool:
dp=[False]*(len(s)+1)
dp[0]=True
for i in range(len(s)+1):
for word in wordDict:
if dp[i] and (i+len(word))<=len(s) and word ==s[i:i+len(word)]:
dp[i+len(word)]=True
return dp[-1]
def wordBreak(self, s: str, wordDict: List[str]) -> bool:
"""
判断字符串 s 是否可以被拆分为一个或多个在字典中出现的单词。
Args:
s: 输入字符串。
wordDict: 包含字典单词的列表。
Returns:
如果 s 可以被拆分,返回 True;否则返回 False。
"""
n = len(s)
# 将列表转换为集合,以提高查找效率 (O(1) 平均时间复杂度)
# Convert list to set for faster lookups (O(1) average time)
wordSet = set(wordDict)
# 初始化 dp 数组
# dp[i] 表示字符串 s 的前 i 个字符 (s[0...i-1]) 是否可以被成功拆分
# Initialize dp array: dp[i] means the prefix of s with length i (s[0...i-1]) can be segmented
dp = [False] * (n + 1)
# 设置基础情况 (Set base case)
# dp[0] 表示空字符串,空字符串总是可以被拆分的
# dp[0] represents the empty string, which is always considered segmentable
dp[0] = True
# 外层循环:遍历所有可能的前缀结束位置(或长度) i
# Outer loop: iterate through all possible prefix end positions (or lengths) i
for i in range(n + 1):
# 只有当 dp[i] 为 True 时,才有可能从位置 i 继续向后匹配
# Only proceed if dp[i] is True, meaning s[0...i-1] is segmentable
# 如果当前位置 i 本身就无法通过之前的单词组合到达,则跳过内层循环
# If the current position i cannot be reached by previous word combinations, skip inner loop
if not dp[i]:
continue
# 内层循环:尝试字典中的每一个单词 word
# Inner loop: try every word in the dictionary (using the set for efficiency)
for word in wordSet:
# 检查条件:
# 1. 当前位置 i 是可达的 (dp[i] is True - 已经在外层if判断了,这里省略也可)
# 2. 加上单词 word 后,新的结束位置 i + len(word) 不能超出字符串 s 的总长度 n
# 3. 从字符串 s 的位置 i 开始,长度为 len(word) 的子字符串,必须与当前的 word 完全相同
# Check conditions:
# 1. Current position i is reachable (dp[i] is True - checked by the outer 'if not dp[i]: continue')
# 2. The new end position i + len(word) must not exceed the total length n of string s
# 3. The substring of s starting at index i with length len(word) must exactly match the current word
if (i + len(word)) <= n and s[i : i + len(word)] == word:
# 如果所有条件都满足,说明我们找到了一个方法可以拆分到新的位置 i + len(word)
# If all conditions are met, it means we found a way to segment up to the new position i + len(word)
# 将该位置标记为可达 (True)
# Mark this new reachable position as True
dp[i + len(word)] = True
# 返回最终结果
# dp[n] (即 dp[-1]) 存储了整个字符串 s 是否可以被成功拆分的结果
# Return the final result: dp[n] (same as dp[-1]) stores whether the entire string s can be segmented
return dp[n]