总结一下Word Break I 和 II

第一题:

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

For example, given
s = "leetcode",
dict = ["leet", "code"].

Return true because "leetcode" can be segmented as "leet code"


第二题:

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


第一题是判断字典里是否存在S的可行的拆分,第二题是求所有可行的拆分。动态规划。第二题需要先利用第一题的结果来判断是否存在拆分,再计算拆分,否则会超时。

class Solution(object):
    def wordBreak(self, s, wordDict):
        """
        :type s: str
        :type wordDict: Set[str]
        :rtype: bool
        """
        partial = [False] * len(s)
        for i in range(len(s)):
            if s[:i+1] in wordDict:
                partial[i] = True
                continue
            for j in range(i-1, -1, -1):
                if partial[j] == True and s[j+1:i+1] in wordDict:
                    partial[i] = True
                    break
        return partial[len(s) - 1]
                    

class Solution(object):
    def wordBreak(self, s, wordDict):
        """
        :type s: str
        :type wordDict: Set[str]
        :rtype: List[str]
        """
        divisible = [False] * len(s)
        for i in range(len(s)):
            if s[:i+1] in wordDict:
                divisible[i] = True
                continue
            for j in range(0, i):
                if divisible[j] and s[j+1:i+1] in wordDict:
                    divisible[i] = True
                    break
        
        results = []
        if not divisible[len(s) - 1]:
            return results
            
        candidates = [[] for i in range(len(s))]
        for i in range(len(s)):
            cur = s[:i+1]
            if cur in wordDict:
                candidates[i].append([cur])
            for j in range(0, i):
                new = s[j+1:i+1]
                if new in wordDict and len(candidates[j]) != 0:
                    for k in candidates[j]:
                        candidates[i].append(k + [new])
                        
        for i in candidates[len(s) - 1]:
            results.append(" ".join(i))
            
        return results


你可能感兴趣的:(Algorithm,LeetCode,面试题)