您的位置:首页 > 其它

139. Word Break

2017-06-26 15:13 260 查看
问题:

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"
.

分析:熊签到后依次遍历,看是否当前字母所在的单词是属于dict的,若不属于时,退出循环,返回false,若循环结束,则返回true

代码:

class Solution {

public:
bool wordBreak(string s, unordered_set<string>& wordDict) {
int len=s.size();
vector<bool> dp(len+1,false);
dp[0]=true;
for(int i=1;i<=len;i++){
for(int j=i-1;j>=0;j--){
if(dp[j]&&wordDict.count(s.substr(j,i-j))){
dp[i]=true;
break;
}
}
}
return dp[len];
}

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