Word Break II

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"].

class Solution:
    # @param s, a string
    # @param dict, a set of string
    # @return a list of strings
    def wordBreak(self, s, dict):
        Solution.res = []
        self.dfs(s, dict, '')
        return Solution.res
        
    def dfs(self, s, dict, stringlist):
        if self.isBreak(s, dict):
            if len(s) == 0: 
                Solution.res.append(stringlist[1:])
            for i in range(1, len(s)+1):
                if s[:i] in dict:
                    self.dfs(s[i:], dict, stringlist+' '+s[:i])
    
        
    def isBreak(self,s,word_dict):
        mark = [ False for i in range(len(s)+1) ]
        mark[0]=True
        for i in range(1,len(s)+1):
            for j in range(0,i):
                if mark[j] and s[j:i] in word_dict:
                    mark[i]=True
                    break
        return mark[-1]



你可能感兴趣的:(leetcode)