题目:https://oj.leetcode.com/problems/word-break/
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"
.
可以用DP的方法解决。
用数组wb[i]保存从0开始到长度为i的子串能否被分割,所以最后的结果返回wb[s.size() - 1]。
首先wb[0] = true.则wb[1]可分割的条件是:wb[0] == true且子串s[0]包含在字典中...wb[i] == true的条件是:存在0 <= j < i,使得从开始长度为j的子串可分割且从j到i的子串存在在字典中...以此类推求出所有的wb[i]...
AC代码:
class Solution {
public:
bool wordBreak(string s, unordered_set<string> &dict) {
int len = s.size();
//创建数组wb[i]表示从0开始长度为i的子串能否被分割;最后的答案则是wb[len]
vector<bool> wb(len + 1,false);
wb[0] = true;
for(int i = 1;i <= s.size();i++){
for(int j = i - 1;j >= 0;j--){
//如果从开始长度为j的子串可以分割而且从j到i的子串出现在字典中
//则从开始长度为i的子串也可以分割
if(wb[j] && dict.count(s.substr(j,i - j))){
wb[i] = true;
break;
}
}
}
return wb[len];
}
};