码迷,mamicode.com
首页 > 其他好文 > 详细

139. Word Break

时间:2017-07-07 17:37:22      阅读:137      评论:0      收藏:0      [点我收藏+]

标签:ack   tar   sep   iter   als   can   last   example   contain   

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

标签:ack   tar   sep   iter   als   can   last   example   contain   

原文地址:http://www.cnblogs.com/prmlab/p/7133049.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!