您的位置:首页 > 其它

139. Word Break 单词切分

2016-07-13 15:38 281 查看
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"
.

1. 与之前答案相同,不要问我怎么做,因为我也是背下来的。。。

class Solution {
public:
bool wordBreak(string s, unordered_set<string>& wordDict) {
int n = s.size();
vector<bool> label(n+1, false);
label[0] = true;
for(int i = 1; i <= n; i++){
for(int j = 1; j <= i; j++){
if(label[i-j] == true){
string str = s.substr(i-j,j);
if(wordDict.find(str) != wordDict.end())
label[i] = true;
}
}
}
return label
;
}
};

2.别人的答案 这个比较好理解

bool wordBreak(string s, unordered_set<string> &dict) {
if(dict.size()==0) return false;

vector<bool> dp(s.size()+1,false);
dp[0]=true;

for(int i=1;i<=s.size();i++)
{
for(int j=i-1;j>=0;j--)
{
if(dp[j])
{
string word = s.substr(j,i-j);
if(dict.find(word)!= dict.end())
{
dp[i]=true;
break; //next i
}
}
}
}

return dp[s.size()];
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  dynamic programming