A Simple Python DP solution


  • 10
    B
    class Solution(object):
        def wordBreak(self, s, wordDict):
            """
            :type s: str
            :type wordDict: Set[str]
            :rtype: bool
            """
            dp = [False] * (len(s) + 1) # dp[i] means s[:i+1] can be segmented into words in the wordDicts 
            dp[0] = True
            for i in range(len(s)):
                for j in range(i, len(s)):
                    if dp[i] and s[i: j+1] in wordDict:
                        dp[j+1] = True
                        
            return dp[-1]

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.