139. Word Break

1. 递归

虽然超时没有通过,我觉得这样做道理上是对的

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

2.动规

重要的就是状态转移方程,res[i] = res[i-1] && wordDict.contains(s.substring(i-1, end))

如果res[i]表示的是,从0开始到index为i-1,即从头开始i位字符有解,那么res[i+1]为的结果是res[0]为真并且字典里有前i位这个词,或者res[1]并且wordDict里面有(1,i)这个词...只要中间有一个是真的,那么就可以这样分解

 1     public boolean wordBreak(String s, Set<String> wordDict) {
 2         if(s == null || s.length() == 0 || wordDict == null) {
 3             return false;
 4         }
 5         int len = s.length();
 6         boolean[] res = new boolean[len+1];
 7         res[0] = true;
 8         for(int i = 1; i <= len; i++) {
 9             for(int j = 0; j < i; j++) {
10                 if(res[j] && wordDict.contains(s.substring(j, i))) {
11                     res[i] = true;
12                     break;
13                 }
14             }
15         }
16         return res[len];
17     }

最差情况是O(n^2)

posted @ 2016-06-20 08:23  warmland  阅读(153)  评论(0编辑  收藏  举报