【Leetcode】139. Word Break

在这里插入图片描述

class Solution1(object):
    def wordBreak(self, s, wordDict):
        """
        传统dp ,先遍历母串再遍历wordDict 看当前的位置是否能被构成
        该方法在 s较小wordDict较大的时候运行效率低
         faster than 85%
        """
        s = " " + s
        dp = [False] * len(s)
        dp[0] = True
        for i in range(1, len(s)):
            for word in wordDict:
                if i >= len(word) and dp[i-len(word)] is True and s[i-len(word)+1:i+1] == word:
                    dp[i] = True
                    break
        return dp[-1]


class Solution2(object):
    def wordBreak(self, s, wordDict):
        """
        wordDict较大的时候适合采取的方法
        dp[i] 表示d s[:i+1]是否能被构成
         faster than 96.68%
        """
        wordSet = set(wordDict)
        s = " " + s
        dp = [False] * len(s)
        dp[0] = True
        for end in range(len(dp)):
            for start in range(1, end + 1):
                if dp[start-1] and s[start:end + 1] in wordSet:
                    dp[end] = True
                    break
        return dp[-1]


class Solution1_1(object):
    """
    solution1的递归形式
    """

    def wordBreak(self, s, wordDict):
        self.memo = {}
        return self.DFS(s, set(wordDict))

    def DFS(self, s, wordSet):
        if len(s) == 0:
            return True
        if len(s) < 0:
            return False
        if s not in self.memo:
            result = False
            for word in wordSet:
                result = False
                if len(s) >= len(word) and s[len(s)-len(word):] == word:
                    result = result or self.DFS(s[:len(s)-len(word)], wordSet)
                    if result :
                        break
            self.memo[s] = result
        return self.memo[s]


class Solution2_1(object):
    """
    solution2的递归形式
    """

    def wordBreak(self, s, wordDict):
        wordSet = set(wordDict)
        self.memo = {}
        return self.DFS(s, wordSet)

    def DFS(self, s, wordSet):
        if len(s) == 0:
            return True
        if s not in self.memo:
            result = False
            for i in range(len(s)):
                if s[i:len(s)] in wordSet:
                    result = result or self.DFS(s[:i], wordSet)
                    if result:
                        break
            self.memo[s] = result
        return self.memo[s]
©️2020 CSDN 皮肤主题: 技术黑板 设计师:CSDN官方博客 返回首页