您的位置:首页 > 其它

LeetCode-Word Break

2013-10-06 00:40 337 查看
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 kmp+动归 复杂度O(n*L) n为字符串长度,L为字典大小

class Solution {
public:
bool wordBreak(string s, unordered_set<string> &dict) {
// Note: The Solution object is instantiated only once and is reused by each test case.
int maxLen=0;
for(unordered_set<string>::iterator it=dict.begin();it!=dict.end();it++){
if( (*it).length()>maxLen)maxLen=(*it).length();
}
string tmp;
vector<bool>acc;
acc.resize(s.length()+1,false);
acc[0]=true;
for(int i=0;i<s.length();i++){
if(acc[i]){
int top=min(maxLen,(int)s.length()-i);
for(int j=1;j<=top;j++){
tmp=s.substr(i,j);
if(dict.find(tmp)!=dict.end()){
acc[i+j]=true;
}
}
}
}
return acc[s.length()];
}
};


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