[leetcode]139. Word Break
2016-09-09 16:22
330 查看
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 =
dict =
Return true because
Subscribe to see which companies asked this question
分析:动态规划,v[i]表示第i个字母不包括这个之前能否被分词;对于比i小的任意一个j,如果j到i的单词在dict内,且v[j]为true,那么v[i]就可以判断为true。
代码:
class Solution {
public:
bool wordBreak(string s, unordered_set<string>& wordDict) {
int n=s.size();
vector<bool> v(n+1,false);
v[0]=true;
for(int i=1;i<=n;i++){
for(int j=i-1;j>=0;j--){
if(v[j]&&wordDict.find(s.substr(j,i-j))!=wordDict.end()){
v[i]=true;
break;
}
}
}
return v
;
}
};
For example, given
s =
"leetcode",
dict =
["leet", "code"].
Return true because
"leetcode"can be segmented as
"leet code".
Subscribe to see which companies asked this question
分析:动态规划,v[i]表示第i个字母不包括这个之前能否被分词;对于比i小的任意一个j,如果j到i的单词在dict内,且v[j]为true,那么v[i]就可以判断为true。
代码:
class Solution {
public:
bool wordBreak(string s, unordered_set<string>& wordDict) {
int n=s.size();
vector<bool> v(n+1,false);
v[0]=true;
for(int i=1;i<=n;i++){
for(int j=i-1;j>=0;j--){
if(v[j]&&wordDict.find(s.substr(j,i-j))!=wordDict.end()){
v[i]=true;
break;
}
}
}
return v
;
}
};
相关文章推荐
- leetcode 139. Word Break
- LeetCode 139 Word Break
- leetcode 139 —— Word Break
- [leetcode]139. Word Break
- Leetcode—139. Word Break
- [leetcode] 139.Word Break
- [LeetCode]139 Word Break
- [Leetcode 139, medium] Word Break
- leetcode 139. Word Break
- Leetcode 139 Word Break
- leetcode 139. Word Break(dp,字典匹配)
- Leetcode 139. Word Break
- [leetcode] 139. Word Break
- Leetcode 139, Word Break
- LeetCode 139. Word Break
- LeetCode-139.Word Break
- Leetcode--139. Word Break
- [leetcode-139]Word Break(java)
- leetcode[139] Word Break
- Leetcode 139. Word Break (Medium) (cpp)