您的位置:首页 > 其它

[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 = 
"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
;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: