[LeetCode]--139. Word Break(Python)

来源:互联网 发布:北京网库 知乎 编辑:程序博客网 时间:2024/06/06 15:49

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

Subscribe to see which companies asked this question
Let’s see the Python Code
Extremely Concise

class Solution(object):    def wordBreak(self, s, wordDict):        """        :type s: str        :type wordDict: Set[str]        :rtype: bool        """        # dp[i] = true means that s[0, i -1] can be constructed by the words in wordDict.        # So, dp[0] must be ture.        n, dp = len(s), [True] + [False] * len(s)        for i in range(n):            for j in range(i + 1):                if dp[j] and s[j:i+1] in wordDict:                    dp[i + 1] = True                    break        return dp[n]
0 0
原创粉丝点击