139. Word Break
# Medium
The problem is where to cut in this string. Record from start to end, if the substring [0: i] can do word break. The result is [0: len(s)-1].
Solution:
Define a list
canSegement[False]*(len(s)+1)to do DP, setcanSegement[0]=True.Two-layer for loop to fill in all elements of canSegment. Cut from
[0:i], if substring before cut can segement and substring after cut is contained inwordDic, thencanSegment[i]=True.canSegment[len(s)]is the result.

class Solution:
def wordBreak(self, s: str, wordDict: List[str]) -> bool:
canSegment = [False]*(len(s)+1)
canSegment[0] = True
for i in range(1, len(s)+1):
for j in range(0, i):
if canSegment[j] == True and s[j:i] in wordDict:
canSegment[i] = True
break
canSegment[i] = False
return canSegment[len(s)]Last updated
Was this helpful?