题目:
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"
.
UPDATE (2017/1/4):
The wordDict parameter had been changed to a list of strings (instead of a set of strings). Please reload the code definition to get the latest changes.
Subscribe to see which companies asked this questio
class Solution {
public:
bool wordBreak(string s, vector<string>& wordDict) {
int size = wordDict.size();
set<string>ma;
for (vector<string> ::iterator iter = wordDict.begin(); iter != wordDict.end(); iter++)ma.insert((*iter));
int len = s.size();
vector<bool>re(len, false);
string temp;
for (int i = 0; i < len; i++){
for (int j = i; j >= 0; j--){
if (re[j] == true){
temp = s.substr(j + 1, i - j);
if (ma.find(temp) != ma.end()){
re[i] = true;
break;
}
}
if (j == 0){
temp = s.substr(0, i + 1);
if (ma.find(temp) != ma.end()){
re[i] = true;
break;
}
}
}
}
return re[len - 1];
}
};
AC代码2:
class Solution {
public:
bool wordBreak(string s, vector<string>& wordDict) {
int size = wordDict.size();
set<string>ma;
for (vector<string> ::iterator iter= wordDict.begin();iter!=wordDict.end(); iter++)ma.insert((*iter));
int len = s.size();
vector<bool>re(len+1,false);
re[0] = true;
string temp;
for (int i = 1; i <=len;i++){
for (int j = i-1; j >= 0;j--){
if (re[j] == true){
temp = s.substr(j, i - j);
if (ma.find(temp) != ma.end()){
re[i] = true;
break;
}
}
}
}
return re[len];
}
};
解析:
AC代码1是自己写的第一个版本,这时需要注意的的一种情况就是当前下标为i的字母要包含下标为0的字母所组成的字符串存在于wordDict中;
AC代码2利用一个额外的存储空间并将re[0]设置为true,这样的好处就是将AC代码1中的特殊情况统一处理,也就是当j递减到0时,那么这时字符串s就会将第
一个字母包含就去,这种统一化处理方式比较妙!