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

[Leetcode]Word Break

2015-02-02 15:24 302 查看
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"
.

用动态规划来做~dp[i]表示到字符串的第i个元素为止能否用字典中的单词表示~

class Solution:
# @param s, a string
# @param dict, a set of string
# @return a boolean
def wordBreak(self, s, dict):
lenS = len(s)
dp = [False for i in xrange(lenS + 1)]
dp[0] = True
for i in xrange(1, lenS + 1):
for j in xrange(i - 1, -1, -1):
if s[j:i] in dict and dp[j]:
dp[i] = True
continue
return dp[lenS]
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode python