首页 > 其他 > 详细

Word Break

时间:2015-06-16 10:36:14      阅读:95      评论:0      收藏:0      [点我收藏+]

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".


 

My first solution   

 1     public boolean wordBreak(String s, Set<String> wordDict) {
 2         return helper(s, wordDict, 0);
 3     }
 4     
 5     public boolean helper(String s, Set<String> wordDict, int pos) {
 6         if(pos >= s.length())
 7             return true;
 8             
 9         boolean res = false;
10         for(int i = pos + 1; i <= s.length(); i++) {
11             String sub = s.substring(pos, i);
12             boolean curr = wordDict.contains(sub);
13             if(curr) {
14                 curr = helper(s, wordDict, i);
15             }
16             res = res || curr;
17             if(res) return true;
18         }
19         return res;
20     }

Note: 

  1. Line 17 处是需要非常注意的,我们并不需要iterate all possibilities, return true if one possibility works.
  2. This code is not effient enough, recursion runtime will grow exponentially. As for String length greater than 30, it takes a lot of time to finish.

 

Word Break

原文:http://www.cnblogs.com/alanluan/p/4579904.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!