您的位置:首页 > 编程语言 > C语言/C++

leetcodeOJ 139. Word Break

2017-04-10 12:03 176 查看
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 = 
"leetcode"
,
dict = 
["leet", "code"]
.

Return true because 
"leetcode"
 can be segmented
as 
"leet code"
.

动态规划
代码如下:
class Solution {
public:
bool wordBreak(string s, vector<string>& wordDict) {
if(wordDict.size() == 0)
return false;

int n = s.size();
vector<bool> dp(n+1, false);
dp[0] = true;
for(int i = 1; i <= n; i++){
for(int j = i-1; j >= 0; j--){
if(dp[j]){
string w = s.substr(j, i-j);
vector<string>::const_iterator re = find(wordDict.begin(), wordDict.end(), w);
if(re != wordDict.end()){
dp[i] = true;
break;
}
}
}
}

return dp
;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息