leetcode 139. Word Break

题目链接:leetcode

思路:
用递归做会超时,发现可以分解为更小的问题,用动态规划

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution(object):
def wordBreak(self, s, wordDict):
"""
:type s: str
:type wordDict: List[str]
:rtype: bool
"""
d = {}
dp = [False]*len(s)
for word in wordDict:
if word not in d:
d[word] = 1
dp[0] = True if s[0] in d else False
for i in range(1,len(s)):
if s[:i+1] in d:
dp[i] = True
continue
for j in range(i):
if dp[j] and s[j+1:i+1] in d:
dp[i] = True
break
return dp[-1]