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

139. Word Break -Medium

2017-02-11 22:23 274 查看

Question

Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, determine if s can be segmented into a space-separated sequence of one or more dictionary words. You may assume the dictionary does not contain duplicate words.

给出一个非空字符串s和一个包含一系列非空单词的字典wordDict,请你确定是否s可以用空格分割出一个或多个字典中的单词。字典中的单词不重复。

Example

*For example, given

s = “leetcode”,

dict = [“leet”, “code”].

Return true because “leetcode” can be segmented as “leet code”.

Solution

动态规划解。定义dp[i]:s[:i]是否在字典中。那么递推式怎么找呢?假设我们要判断dp[i]是否在字典中,如果我们已知dp[j]在字典中(j < i),那么如果我们又判断得到s[j+1:i]也在字典中,那么我们就可以知道dp[i]在字典中了。即 dp[i] = dp[j] and s[j+1:i] in wordDict (j < i)

class Solution(object):
def wordBreak(self, s, wordDict):
"""
:type s: str
:type wordDict: List[str]
:rtype: bool
"""
dp = [True] + [False] * len(s)
for index_s in range(1, len(s) + 1):
for j in range(index_s):
# 如果前j个已经可以在字典中找到且j+1:index_s也在字典中(因为index的范围是1 -- len(s) + 1,所以写j:index_s)
if dp[j] and s[j:index_s] in wordDict:
# 代表前index_s个字符串可以在字典中找到(包括分解找到)
dp[index_s] = True
break
return dp[-1]
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息