总结一下Word Break I 和 II
来源:互联网 发布:mac拼音怎么打 编辑:程序博客网 时间:2024/05/17 22:47
第一题:
Given a string s and a dictionary of words dict, determine ifs can be segmented into a space-separated sequence of one or more dictionary words.
For example, given
s = "leetcode"
,
dict = ["leet", "code"]
.
"leetcode"
can be segmented as "leet code"
第二题:
Given a string s and a dictionary of words dict, add spaces ins to construct a sentence where each word is a valid dictionary word.
Return all such possible sentences.
For example, given
s = "catsanddog"
,
dict = ["cat", "cats", "and", "sand", "dog"]
.
A solution is ["cats and dog", "cat sand dog"]
.
第一题是判断字典里是否存在S的可行的拆分,第二题是求所有可行的拆分。动态规划。第二题需要先利用第一题的结果来判断是否存在拆分,再计算拆分,否则会超时。
class Solution(object): def wordBreak(self, s, wordDict): """ :type s: str :type wordDict: Set[str] :rtype: bool """ partial = [False] * len(s) for i in range(len(s)): if s[:i+1] in wordDict: partial[i] = True continue for j in range(i-1, -1, -1): if partial[j] == True and s[j+1:i+1] in wordDict: partial[i] = True break return partial[len(s) - 1]
class Solution(object): def wordBreak(self, s, wordDict): """ :type s: str :type wordDict: Set[str] :rtype: List[str] """ divisible = [False] * len(s) for i in range(len(s)): if s[:i+1] in wordDict: divisible[i] = True continue for j in range(0, i): if divisible[j] and s[j+1:i+1] in wordDict: divisible[i] = True break results = [] if not divisible[len(s) - 1]: return results candidates = [[] for i in range(len(s))] for i in range(len(s)): cur = s[:i+1] if cur in wordDict: candidates[i].append([cur]) for j in range(0, i): new = s[j+1:i+1] if new in wordDict and len(candidates[j]) != 0: for k in candidates[j]: candidates[i].append(k + [new]) for i in candidates[len(s) - 1]: results.append(" ".join(i)) return results
0 0
- 总结一下Word Break I 和 II
- leetCode: Word Break I & Word Break II
- 【LeetCode】word break I && II
- leetcode word break I && II
- leetcode Word Break I II 算法分析
- LeetCode题解:Word Break I and II
- leetcode day7 -- Word Break I II
- Sudoku Solver & Word Break I && *II
- dp 专题:1 Word Break I II
- leetcode -- Word Break I & II -- 重点
- Leetcode 139. Word Break I&&II
- leetcode题目:Word Break和Word Break II
- Word Break && Word Break II
- Word Break && Word Break II
- Word Break I,II, Triangle,Palindrome Partitioning 动态规划 DP
- leetcode做题总结,动态规划I(Triangle,Unique PathsI/II,Minimum Path Sum,Climbing Stairs,Jump Game,Word Break)
- [leetcode]Word Break II
- Word Break II
- ———
- visio制作图形的基本技巧
- Ubuntu kylin-14.04 下配置 Hadoop 一:环境配置
- Ubuntu kylin-14.04 下配置 Hadoop 二:安装hadoop(单机模式)
- Use Unicode and Hide the Console in Windows
- 总结一下Word Break I 和 II
- Longest Increasing Subsequence
- hadoop配置文件及常用配置
- ajax 的简述与原理
- ——黑马程序员——OC中NSNumber、NSValue、NSDate 的使用总结
- LeetCode Edit Distance
- 冒泡排序:JAVA
- LeetCode 题解(284) : Smallest Rectangle Enclosing Black Pixels
- 直接插入排序 :Java实现