代码随想录 动态规划 day46

139. 单词拆分

class Solution:
    def wordBreak(self, s: str, wordDict: List[str]) -> bool:
        wordSet = set(wordDict)
        n = len(s)
        dp = [False for_ in range(n + 1)]  
        dp[0] = True  

        for i in range(1, n + 1):
            for j in range(i):
                如果 s[0:j] 可以被拆分成单词,并且 s[j:i] 在单词集合中存在,则 s[0:i] 可以被拆分成单词
                if dp[j] and s[j:i] in wordSet:
                    dp[i] = True 
                    break

        return dp[n]

你可能感兴趣的:(动态规划,算法)