import copy
class Solution:
def wordBreak(self, s: str, wordDict: List[str]) -> bool:
dp =[0 for i in range(len(s)+1)]
words=set(wordDict)
dp[0]=1
for i in range(1,len(s)+1):
for j in range(i-1,-1,-1):
if dp[j]==0:continue
if s[j:i] in words:
dp[i]=1
break
return dp[len(s)]
class Solution:
def wordBreak(self, s: str, wordDict: List[str]) -> bool:
dp={-1: True}
for i in range(len(s)):
for word in wordDict:
if i-len(word) in dp and s[i-len(word)+1:i+1]==word:
dp[i]=True
return len(s)-1 in dp
这个题枚举word更快