139. Word Break
2017-06-11 22:56
120 查看
题目:
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
链接: http://leetcode.com/problems/word-break/
6/11/2017
自己做的brute force DFS超时了
注意,到今天为止leetcode的testcase不全,有可能会放过错误的代码,用这个testcase试一下
"cdbbbbbaaa"
["cdb","bbb", "cdbb", "aaa"]
官方讲解
https://leetcode.com/articles/word-break/
自己准备做一下BFS和DP
BFS
注意的问题:
1. i的意思其实是end position,第19行应该是<= s.length(),原因是当前的end有可能被放入queue作为下一次的起点,并且substring(start, end)是不包括end位置上的char的
2. 第14, 15行可以早点退出函数
DP留给之后
更多讨论
https://discuss.leetcode.com/category/147/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 =
"leetcode",
dict =
["leet", "code"].
Return true because
"leetcode"can be segmented as
"leet code".
链接: http://leetcode.com/problems/word-break/
6/11/2017
自己做的brute force DFS超时了
注意,到今天为止leetcode的testcase不全,有可能会放过错误的代码,用这个testcase试一下
"cdbbbbbaaa"
["cdb","bbb", "cdbb", "aaa"]
官方讲解
https://leetcode.com/articles/word-break/
自己准备做一下BFS和DP
BFS
注意的问题:
1. i的意思其实是end position,第19行应该是<= s.length(),原因是当前的end有可能被放入queue作为下一次的起点,并且substring(start, end)是不包括end位置上的char的
2. 第14, 15行可以早点退出函数
1 public class Solution { 2 public boolean wordBreak(String s, List<String> wordDict) { 3 Set<String> set = new HashSet<String>(wordDict); 4 Queue<Integer> queue = new LinkedList<Integer>(); 5 boolean[] visited = new boolean[s.length()]; 6 7 queue.add(0); 8 while (!queue.isEmpty()) { 9 int start = queue.poll(); 10 if (!visited[start]) { 11 for (int i = start + 1; i <= s.length(); i++) { 12 if (set.contains(s.substring(start, i))) { 13 queue.add(i); 14 if (i == s.length()) { 15 return true; 16 } 17 } 18 } 19 visited[start] = true; 20 } 21 } 22 return false; 23 } 24 }
DP留给之后
更多讨论
https://discuss.leetcode.com/category/147/word-break
相关文章推荐
- LeetCode 139 Word Break
- LeetCode139:Word Break
- LeetCode(139) Word Break
- leetcode 139: Word Break
- LeeCode_139 Word Break
- [LeetCode]题解(python):139-Word Break
- LeetCode *** 139. Word Break
- 139. Word Break(难)
- LeetCode139—Word Break
- 139 Word Break
- 139. Word Break
- 139 Word Break
- LeetCode - 139/140 - Word Break
- 139. Word Break
- 139. Word Break
- leetcode 139. Word Break
- 139. Word Break
- LeetCode(139)Word Break
- Leetcode#139 Word Break
- leetcode[139]Word Break