您的位置:首页 > 编程语言 > Python开发

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

2016-08-08 18:11 423 查看
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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: