首页 > 其他 > 详细

Word Break

时间:2015-04-10 06:54:49      阅读:171      评论: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".

这题拿到就开始硬做。。是不对滴。用DP做怎样?搞清楚state,function,initialize和result。

 1 public boolean wordBreak(String s, Set<String> dict) {
 2         int maxWordLen = 0;
 3         for (String str : dict) {
 4             maxWordLen = Math.max(maxWordLen, str.length());
 5         }
 6         //F[i] 代表在i时,前面的是否可以被字典中的词拆分
 7         //F[i] = (F[j] && dict.contains(s.substring(j ,i)))
 8         //F[0] = true;
 9         //return F[s.length()]
10         boolean[] F = new boolean[s.length() + 1];
11         F[0] = true;
12         for (int i = 1; i <= s.length(); i++) {
13             F[i] = false;
14             for (int j = 0; j < i && j <= maxWordLen; j++) {
15                 if (F[i - j - 1] && dict.contains(s.substring(i - j - 1, i))){
16                     F[i] = true;
17                 }
18             }
19         }
20         return F[s.length()];
21     }

 

Word Break

原文:http://www.cnblogs.com/gonuts/p/4413402.html

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