139. Word Break
2017-01-05 22:22
162 查看
Given a non-empty string s and a dictionary wordDict containing a list of
non-empty words, determine if s can be segmented into a space-separated sequence of one or more dictionary words. You may assume the dictionary does not contain duplicate words.
For example, given
s =
dict =
Return true because
DP思想,用一个dp的bool数组记录s中某位是否为word中某单词的末尾位,对于每一位,向前找到上一个dp中为1的地方,然后检查这两位之间的子字符串是否存在于dict里面。
dicuss上的解法讲的有问题害我理解了好久……
比如有一个数组dp,那么对于“leetcode”这个字符串来说,值为1的位应该是0,4,8而不是discuss里面说的0,3,7
class Solution {
public:
bool wordBreak(string s, vector<string>& wordDict) {
//if(wordDict.size()==0) return 0;
vector<bool> dp(s.size()+1, 0);//这里是s.size+1,就是要多分配一位
dp[0]=1;
for(int i=1; i<=s.size(); i++){//这里的循环条件是i<=s.size(),为了令j可以取到数组最后一位
for(int j=i-1; j>=0; j--){
if(dp[j]){
string sub=s.substr(j, i-j);
if(find(wordDict.begin(), wordDict.end(), sub)!=wordDict.end()){//注意vector没有find函数,要用算法里的函数
dp[i]=1;
break;
}
}
}
}
return dp[s.size()];
}
};
non-empty words, determine if s can be segmented into a space-separated sequence of one or more dictionary words. You may assume the dictionary does not contain duplicate words.
For example, given
s =
"leetcode",
dict =
["leet", "code"].
Return true because
"leetcode"can be segmented as
"leet code".
DP思想,用一个dp的bool数组记录s中某位是否为word中某单词的末尾位,对于每一位,向前找到上一个dp中为1的地方,然后检查这两位之间的子字符串是否存在于dict里面。
dicuss上的解法讲的有问题害我理解了好久……
比如有一个数组dp,那么对于“leetcode”这个字符串来说,值为1的位应该是0,4,8而不是discuss里面说的0,3,7
class Solution {
public:
bool wordBreak(string s, vector<string>& wordDict) {
//if(wordDict.size()==0) return 0;
vector<bool> dp(s.size()+1, 0);//这里是s.size+1,就是要多分配一位
dp[0]=1;
for(int i=1; i<=s.size(); i++){//这里的循环条件是i<=s.size(),为了令j可以取到数组最后一位
for(int j=i-1; j>=0; j--){
if(dp[j]){
string sub=s.substr(j, i-j);
if(find(wordDict.begin(), wordDict.end(), sub)!=wordDict.end()){//注意vector没有find函数,要用算法里的函数
dp[i]=1;
break;
}
}
}
}
return dp[s.size()];
}
};
相关文章推荐
- [leetcode 139] Word Break
- 【LeetCode】139 - Word Break
- [leetcode] 139 Word Break
- LeetCode 139. Word Break
- 139. Word Break(dp)
- 139. Word Break
- 139. Word Break
- leetcode 139. Word Break
- 139. Word Break
- 139. Word Break
- leetcode 139 —— Word Break
- leetcode 139. Word Break
- LeetCode 139. Word Break(单词分隔)
- leetcode 139. Word Break(dp,字典匹配)
- 139. Word Break
- Leetcode题解 - 139. Word Break
- 第十一周:[Leetcode]139. Word Break
- Leetcode--139. Word Break
- [LeetCode] 139 Word Break(BFS统计层数的方法)
- Leetcode 139. Word Break