[Lintcode]107. Word Break/[Leetcode]139. Word Break

107. Word Break/139. Word Break

  • 本题难度: Medium
  • Topic: Dynamic Programming

Description

Given a string s and a dictionary of words dict, determine if s can be break into a space-separated sequence of one or more dictionary words.

Example
Example 1:
Input: "lintcode", ["lint", "code"]
Output: true

Example 2:
Input: "a", ["a"]
Output: true

我的代码

    def wordBreak(self, s, dict):
        # write your code here
        l = len(s)
        if len(dict) == 0:
            if l == 0:
                return True
            else:
                return False
        res = [1] + [0 for i in range(1,l)]
        while(sum(res)>0):
            left = -1
            for i in range(left+1,l):
                if left<0 and res[i] == 1:
                    left = i
                    res[i] = 0
                if s[left:i+1] in dict:
                    if i == l-1:
                        return True
                    res[i+1] = 1
        return False

别人的代码

参考:https://www.jiuzhang.com/solutions/word-break/#tag-highlight-lang-python

class Solution:
    # @param s: A string s
    # @param dict: A dictionary of words dict
    def wordBreak(self, s, dict):
        if len(dict) == 0:
            return len(s) == 0
            
        n = len(s)
        f = [False] * (n + 1)
        f[0] = True
        
        maxLength = max([len(w) for w in dict])
        for i in range(1, n + 1):
            for j in range(1, min(i, maxLength) + 1):
                if not f[i - j]:
                    continue
                if s[i - j:i] in dict:
                    f[i] = True
                    break
        
        return f[n]

思路
从左到右多次循环。在确定左边可分之后,开始讨论右边。
有很多可简化的空间。

s = "catsandog", wordDict = ["cats", "dog", "sand", "and", "an", "cat"]


 c a t s a n d o g
 1 0 0 0 0 0 0 0 0
 0 0 0 1 1 0 0 0 0
 0 0 0 0 0 0 0 1 0
 0 0 0 0 0 0 1 1 0
 0 0 0 0 0 0 0 0 0 #

我的代码Leetcode可以通过,但是Lintcode通过不了。以后再看别人的代码。

  • 时间复杂度 O(n^2)
posted @ 2019-02-17 03:46  siriusli  阅读(140)  评论(0编辑  收藏  举报