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

Word Break

时间:2015-06-16 10:36:34      阅读:131      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!