动态规划题目笔记(一):LeetCode

139.Word Break

Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, determine if s can be segmented into a space-separated sequence of one or more dictionary words.

Note:
The same word in the dictionary may be reused multiple times in the segmentation.
You may assume the dictionary does not contain duplicate words.

class Solution:
    def wordBreak(self, s: str, wordDict: List[str]) -> bool:
        size=len(s)
        assert size>0
        word_set={word for word in wordDict}
        dp=[False for _ in range(size+1)]
        dp[0]= True #保证空字符串为True

        for r in range(1,size+1):
            for l in range(r):
                #划分子问题,当子单词的孙子单词左右都为True时
                #说明几个孙子单词都在word_set,即这个子单词划分成功
                #将这个子单词标记为True,再上升最终将整个str标记为True
                if dp[l] and s[l:r] in word_set:
                    dp[r]=True
                    break #提升效率,r已经为True,l不必继续
        return dp[-1]

猜你喜欢

转载自www.cnblogs.com/shitianfang/p/12631002.html