您的位置:首页 > 其它

139 Word Break

2015-12-24 21:39 218 查看
题目链接:https://leetcode.com/problems/word-break/

题目:

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


解题思路:

这题的考点依然是动态规划

说起动态规划,先考虑它的状态转换是怎样的。

1. 对于这道题来说,从下标为 0 的字符到当前字符 i 这个子串是否可切分为字典单词——这个状态可以记录到数组 res[i] 中。

2. i + 1 到 j 这个子串若能拆分为字典中的单词,并且 0 到 i 这个子串也能被拆分为单词,即 res[i] 为 true,那么 0 到 j 这个子串就能被切分为字典单词,即 res[j] = true。

3. 我们不必关注 0 到 i 这个子串是如何被切分的。也就是动态规划中用空间做缓存保存有价值的状态。

4. 递推式为:res[j] = res[i] && wordDict.contains(s.substring(i + 1, j))

我和大神的思路稍有不同。

但,大神比我说的好,附上大神的思考:/article/1378286.html

这道题仍然是动态规划的题目,我们总结一下动态规划题目的基本思路。

1. 首先我们要决定要存储什么历史信息以及用什么数据结构来存储信息。

2. 然后是最重要的递推式,就是如从存储的历史信息中得到当前步的结果。

3. 最后我们需要考虑的就是起始条件的值。

接下来我们套用上面的思路来解这道题。

1. 首先我们要存储的历史信息 res[i] 是表示到字符串 s 的第 i 个元素为止能不能用字典中的词来表示,我们需要一个长度为 n 的布尔数组来存储信息。

2. 然后假设我们现在拥有 res[0,…,i-1] 的结果,我们来获得 res[i] 的表达式。

3. 思路是对于每个以 i 为结尾的子串,看看他是不是在字典里面以及他之前的元素对应的 res[j] 是不是 true,如果都成立,那么 res[i] 为 true,写成式子是



假设总共有 n 个字符串,并且字典是用 HashSet 来维护,那么总共需要 n 次迭代,每次迭代需要一个取子串的 O(i) 操作,然后检测i个子串,而检测是 constant 操作。所以总的时间复杂度是 O(n^2)(i 的累加仍然是 n^2 量级),而空间复杂度则是字符串的数量,即 O(n)。

代码实现:

自己的思路:

public class Solution {
public boolean wordBreak(String s, Set<String> wordDict) {
if(s == null || s.length() == 0)
return false;
boolean[] res = new boolean[s.length()];
for(int i = 0; i < s.length(); i ++) {
for(int j = i; j < s.length(); j ++) {
// String tmp = s.substring(i, j + 1);
if(wordDict.contains(s.substring(i, j + 1))) {
if(i > 0 && res[i - 1])
res[j] = true;
else if(i == 0)
res[j] = true;
}
}
}
return res[s.length() - 1];
}

}


32 / 32 test cases passed.
Status: Accepted
Runtime: 12 ms


大神的思路:

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

}


32 / 32 test cases passed.
Status: Accepted
Runtime: 11 ms
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: