码迷,mamicode.com
首页 > 其他好文 > 详细

139. Word Break

时间:2017-06-12 00:41:29      阅读:137      评论:0      收藏:0      [点我收藏+]

标签:http   set   example   position   for   testcase   and   问题:   sem   

题目:

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

139. Word Break

标签:http   set   example   position   for   testcase   and   问题:   sem   

原文地址:http://www.cnblogs.com/panini/p/6986780.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!