LeetCode 139. Word Break(单词分隔)
2016-05-27 00:22
393 查看
原题网址:https://leetcode.com/problems/word-break/
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 =
dict =
Return true because
方法一:递归+记忆化搜索。
方法二:动态规划。
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".
方法一:递归+记忆化搜索。
public class Solution { private boolean[] visited; private boolean[] canBreak; private boolean dp(String s, int to, Set<String> wordDict) { if (to == 0) return true; if (visited[to-1]) return canBreak[to-1]; for(int i=0; i<to; i++) { if (wordDict.contains(s.substring(i)) && dp(s.substring(0,i), i, wordDict)) { visited[to-1] = true; canBreak[to-1] = true; return true; } } visited[to-1] = true; canBreak[to-1] = false; return false; } public boolean wordBreak(String s, Set<String> wordDict) { visited = new boolean[s.length()]; canBreak = new boolean[s.length()]; return dp(s, s.length(), wordDict); } }
方法二:动态规划。
public class Solution { public boolean wordBreak(String s, Set<String> wordDict) { if (null == s || "".equals(s)) return true; boolean[] canBreak = new boolean[s.length()]; canBreak[0] = wordDict.contains(s.substring(0,1)); for(int i=1; i<s.length(); i++) { if (wordDict.contains(s.substring(0, i+1))) { canBreak[i] = true; } else { for(int j=0; j<i; j++) { if (canBreak[j] && wordDict.contains(s.substring(j+1, i+1))) { canBreak[i] = true; break; } } } } return canBreak[canBreak.length-1]; } }
相关文章推荐
- LeetCode 138. Copy List with Random Pointer(拷贝随机指针)
- LeetCode 137. Single Number II(单个数字)
- LeetCode 136. Single Number(单个数字)
- LeetCode 135. Candy(糖果)
- LeetCode 134. Gas Station(加油站)
- LeetCode 132. Palindrome Partitioning II(回文切分)
- LeetCode 133. Clone Graph(克隆图)
- 原型链(__proto__)
- makefile之VPATH和vpath的使用
- System.in.read()
- javascript的 Object 和 Function
- 快速多人游戏(1) - 介绍
- 概率世界
- 如何配置php运行环境
- Share Ubuntu Home Directories using Samba
- php性能测试工具--xhprof
- linux篇——centOs下的vim配置
- dll 子类化 记事本 相应自己的功能
- 用NSMutableAttributedString快速设置UIbutton Title/lable的文字:字体,大小,颜色
- 拦截器getmodel方法什么时候被调用(没搞懂有什么鸟用,自己搭的项目中用到了这个)