1、题目描述
https://leetcode-cn.com/problems/word-break/
给定一个非空字符串 s 和一个包含非空单词列表的字典 wordDict,判定 s 是否可以被空格拆分为一个或多个在字典中出现的单词。说明:
- 拆分时可以重复使用字典中的单词。
- 你可以假设字典中没有重复的单词。
2、代码详解
动态规划
class Solution(object):
def wordBreak(self, s, wordDict):
"""
:type s: str
:type wordDict: List[str]
:rtype: bool
"""
n = len(s)
# dp[i] 表示 s 的前 i 位是否可以用 wordDict 中的单词表示
dp = [False] * (n + 1)
dp[0] = True # 空字符可以被表示
for i in range(n): # 开始索引 i,遍历区间 [0,n)
for j in range(i + 1, n + 1): # 结束索引 j,遍历区间 [i+1,n+1)
# dp[i]=True 说明 s 的前 i 位可以用 wordDict 表示,
# 则 s[i,⋯,j) 出现在 wordDict 中,说明 s 的前 j 位可以表示。
if dp[i] == True and (s[i:j] in wordDict):
dp[j] = True
return dp[-1]
s = "applepenapple"
wordDict = ["apple", "pen"] # apple pen apple,可以重复使用字典中的单词
s1 = "catsandog"
wordDict1 = ["cats", "dog", "sand", "and", "cat"] # FALSE 因为and 和 dog 有 重叠 d
S = Solution()
print(S.wordBreak(s, wordDict))
print(S.wordBreak(s1, wordDict1))