LeetCode 139. Word Break
考点 | 难度 |
---|---|
Hash Map | Medium |
题目
Given a string s
and a dictionary of strings wordDict
, return true
if s
can be segmented into a space-separated sequence of one or more dictionary words.
Note that the same word in the dictionary may be reused multiple times in the segmentation.
思路
每个词开始和结尾的index在d[i]
里保存为true
, 其他为false
。判断条件是substring在words里而且substring的开始位置是false
(不和前面的词重复用一些字母)或者string的开始。最后返回d里的最后一位。
答案
class Solution:
def wordBreak(self, s, words):
d = [False] * len(s)
for i in range(len(s)):
for w in words:
if w == s[i-len(w)+1:i+1] and (d[i-len(w)] or i-len(w) == -1):
d[i] = True
return d[-1]