您的位置:首页 > 其它

[Leetcode] Word Break

2014-04-09 14:09 323 查看
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字典中最短单词到最长单词的长度就可以了。

class Solution {
public:
/**
* @param s: A string s
* @param dict: A dictionary of words dict
*/
bool wordBreak(string s, unordered_set<string> &dict) {
// write your code here
vector<bool> dp(s.length() + 1, false);
dp[0] = true;
int min_len = INT_MAX, max_len = INT_MIN;
for (auto &ss : dict) {
min_len = min(min_len, (int)ss.length());
max_len = max(max_len, (int)ss.length());
}
for (int i = 0; i < s.length(); ++i) if(dp[i]) {
for (int len = min_len; i + len <= s.length() && len <= max_len; ++len) {
if (dict.find(s.substr(i, len)) != dict.end())
dp[i + len] = true;
}
if (dp[s.length()]) return true;
}
return dp[s.length()];
}
};


再看个非动规的版本:

class Solution {
public:
bool wordBreakHelper(string s,unordered_set<string> &dict,set<string> &unmatched,int mn,int mx) {
if(s.size() < 1) return true;
int i = mx < s.length() ? mx : s.length();
for(; i >= mn ; i--)
{
string preffixstr = s.substr(0,i);
if(dict.find(preffixstr) != dict.end()){
string suffixstr = s.substr(i);
if(unmatched.find(suffixstr) != unmatched.end())
continue;
else
if(wordBreakHelper(suffixstr, dict, unmatched,mn,mx))
return true;
else
unmatched.insert(suffixstr);
}
}
return false;
}
bool wordBreak(string s, unordered_set<string> &dict) {
// Note: The Solution object is instantiated only once.
if(s.length() < 1) return true;
if(dict.empty()) return false;
unordered_set<string>::iterator it = dict.begin();
int maxlen=(*it).length(), minlen=(*it).length();
for(it++; it != dict.end(); it++)
if((*it).length() > maxlen)
maxlen = (*it).length();
else if((*it).length() < minlen)
minlen = (*it).length();
set<string> unmatched;
return wordBreakHelper(s,dict,unmatched,minlen,maxlen);
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: