Leetcode: Word Break II

Question

Given a string s and a dictionary of words dict, add spaces in s to construct a sentence where each word is a valid dictionary word.

Return all such possible sentences.

For example, given
s = “catsanddog”,
dict = [“cat”, “cats”, “and”, “sand”, “dog”].

A solution is [“cats and dog”, “cat sand dog”].

Show Tags
Show Similar Problems

Solution

Get idea from here.

should check whether this string could be broke, then do dfs.

should see the explanation again.

class Solution(object):
    def wordBreak(self, s, wordDict):
        """ :type s: str :type wordDict: Set[str] :rtype: List[str] """

        res = []
        if s=='':
            return res
        self.helper(s, wordDict, 0, '', res)
        return res

    def helper(self, s, wordDict, start, item, res):
        if self.check(s,wordDict):
            if start==len(s):
                res.append(item[:-1])
                return            

            for ind in range(start,len(s)):
                if s[start:ind+1] in wordDict:
                    self.helper(s, wordDict, ind+1, item+s[start:ind+1]+' ', res)

    def check(self, s, words):
        dp = [False]*(len(s)+1)
        dp[0] = True
        for i in range(1, len(s)+1):
            for k in range(0,i):
                if dp[k] and s[k:i] in words:
                    dp[i] = True
        return dp[-1]

你可能感兴趣的:(Leetcode: Word Break II)