139. Word Break

Posted Premiumlab

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了139. Word Break相关的知识,希望对你有一定的参考价值。

https://leetcode.com/problems/word-break/#/description

 

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. You may assume the dictionary does not contain duplicate words.

For example, given
s = "leetcode",
dict = ["leet", "code"].

Return true because "leetcode" can be segmented as "leet code".

UPDATE (2017/1/4):
The wordDict parameter had been changed to a list of strings (instead of a set of strings). Please reload the code definition to get the latest changes.

 

Sol:

 

DP.

 

Straightforward. Split the input string s into all possible two substrings and check if them are in the word dictionary.

 

Create a status variable dp to track if string s[:i+1] can be splited into two words of the word dictionary. You see, we track the string bit by bit and the next status is based on the previous status. The last status is our concern, and the last element in dp[-1] will be returned. 

 

 

class Solution(object):
    def wordBreak(self, s, wordDict):
        """
        :type s: str
        :type wordDict: List[str]
        :rtype: bool
        """
        
        # dp[i] means s[:i+1] can be segmented into words in the wordDicts
        dp = [False] * (len(s) + 1)
        dp[0] = True
        for spliter1 in range(len(s)):
            for spliter2 in range(spliter1, len(s)):
                if dp[spliter1] and s[spliter1: spliter2 + 1] in wordDict:
                    dp[spliter2 + 1] = True
                    
        return dp[-1]

 

以上是关于139. Word Break的主要内容,如果未能解决你的问题,请参考以下文章

139. Word Break

139. Word Break

139. Word Break

139. Word Break

LeetCode 139. Word Break

139. Word Break