您的位置:首页 > 其它

leetcode之Word Break

2013-11-13 22:49 239 查看
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"
.

思路:先找出dict中字符串的最大长度和最小长度,再遍历s,获取s中的子串,查找该子串是否在dict中,若在继续往后查找

代码如下:

class Solution {
public:
bool wordBreak(string s, unordered_set<string> &dict) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
unordered_set<string>::iterator it = dict.begin();
int maxLen = 0, minLen=1000;
while(it!=dict.end()){
if(maxLen < (*it).length()) maxLen = (*it).length();
if(minLen > (*it).length()) minLen = (*it).length();
it++;
}
int start = 0;
while(start < s.length()){
int cur = start;
for(int i=maxLen;i>=minLen;i--){
if(start+i>s.length()) continue;
string sub = s.substr(start,i);
if(dict.count(sub)){
start = start + i;
break;
}
}
if(start == cur) return false;
}
return true;

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