您的位置:首页 > 其它

139. Word Break

2017-09-11 21:16 127 查看
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) {
int length = s.length();
if(wordDict.size() == 0 && length > 0)
return false;
//        return dfs(s,wordDict,0);
vector<bool> flag(length + 1,false);
flag[0] = true;
for(int i = 1; i <= length; i ++){
for(int j = i - 1; j >= 0; j --){
string temp = s.substr(j, i - j);
if(flag[j] && find(wordDict.begin(),wordDict.end(),temp) != wordDict.end()){
flag[i] = true;
break;
}
}
}
return flag[length];
}

bool dfs(string s, vector<string>& wordDict, int index){
int length = s.length();
if(index >= length)
return true;
string temp;
for(int i = index; i < length; i ++){
temp = s.substr(index, i - index + 1);
if(find(wordDict.begin(),wordDict.end(),temp) != wordDict.end())
if(dfs(s,wordDict,i + 1))
return true;
}
return false;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: