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]
原文地址:https://www.cnblogs.com/prmlab/p/7133049.html