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, givens = “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]
相关文章推荐
- Medium 139题 Word Break
- [Leetcode 139, medium] Word Break
- 【Medium】139. Word Break
- Leetcode 139. Word Break (Medium) (cpp)
- LeetCode 139. Word Break (Medium)
- 【LeetCode】139. Word Break
- leetcode 139. Word Break
- [leedcode 139] Word Break
- leetcode 139. Word Break
- Word Break(medium)
- 139. Word Break
- LeetCode 139 Word Break
- 139. Word Break
- leetcode 139. Word Break
- 【LeetCode-面试算法经典-Java实现】【139-Word Break(单词拆分)】
- [leetcode] 139.Word Break
- [LeetCode]139. Word Break
- [leetcode] 139. Word Break
- [leetcode]139. Word Break
- leetcode 139. Word Break(dp,字典匹配)