您的位置:首页 > 其它

[Leetcode]Word Break

2015-11-08 16:30 316 查看
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"
.

class Solution {
public:
/*algorithm: DFS + hash
*/
bool dfs(string &s,int start,unordered_set<string>& wordDict,unordered_set<string>& unmatched)
{
if(start == s.size())return true;
for(int l = s.size()-start;l >= 1;l--){
string word = s.substr(start,l);
if(wordDict.count(word)){
if(unmatched.count(s.substr(start+l)))continue;//add this,otherwise TME
if(dfs(s,start+l,wordDict,unmatched)){
return true;
}
}else{
if(!unmatched.count(word))
unmatched.insert(word);
}
}
return false;
}
bool wordBreak(string s, unordered_set<string>& wordDict) {
unordered_set<string> dict;
return dfs(s,0,wordDict,dict);
}
};
class Solution {
public:
/*algorihtm
dp(i,j): define substr(i,j) can word break
dp(0,n) = 1 if dp(0,i) and dp(i+1,n) can word break
*/
bool wordBreak(string s, unordered_set<string>& wordDict) {
int n = s.size();
vector<vector<int> >dp(n,vector<int>(n,0));
for(int i = 0;i < n;i++){
for(int j = i;j < n;j++){
string word = s.substr(i,j-i+1);
if(wordDict.count(word)){
dp[i][j]=1;
if(dp[0][i-1])dp[0][j]=1;
}
}
}
return dp[0][n-1];
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: