您的位置:首页 > 其它

leetcode: Word Break

2016-07-05 23:03 323 查看

问题描述:

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

原问题链接:https://leetcode.com/problems/word-break/

 

问题分析

  从问题的要求来看,需要判断是否可以将给定的字符串拆分成若干个子串,使得里面每个子串都可以在给定的字典集中找到。从一种最通用的情况来看,假定一个数组的长度为n。对于里面索引位置为i的点,假设存在有i到n的这一段在集合中可以找到,那么我们这个问题是否有解就取决于前面0到i - 1的这一段的情况了。相当于我们这个问题递归的缩小到更小的串里面了。

  而从问题最小的形式来看,对于长度为0的串,我们可以认为它是可以在字典集合中找到的。这样,我们就构成了一个简单的递推关系:

f(n) = for(i = 0; i < n; i++) { if(s.substring(i, n) in set)  then f(i) is a possible solution }

  既然是这么一个递归的关系,我们如果直接用递归的话,会发现有一些子串的递归情况可能会反复用到。这样可以考虑用动态规划的方法。

  在详细的实现里,我们定义一个boolean[n + 1]canBrerak的串。canBreak[0] = true。表示0个字符的情况。对于后续的元素,我们根据前面的条件来判断设置canBreak[i]的值。只要找到一个满足canBreak[i]为true的值,我们就可以继续考虑canBreak[i+1]的情况了。

  详细的代码实现如下:

 

public class Solution {
public boolean wordBreak(String s, Set<String> dict) {
if(s == null || s.length() == 0) return true;
boolean[] canBreak = new boolean[s.length() + 1];
canBreak[0] = true;
for(int i = 1; i <= s.length(); i++) {
for(int j = 0; j < i; j++) {
if(canBreak[j] && dict.contains(s.substring(j, i))) {
canBreak[i] = true;
break;
}
}
}
return canBreak[s.length()];
}
}

 

阅读更多
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: