题目如下:
给定一个字符串s和一组单词dict,判断s是否可以用空格分割成一个单词序列,使得单词序列中所有的单词都是dict中的单词(序列可以包含一个或多个单词)。
例如:
给定s=“leetcode”;
dict=["leet", "code"].
返回true,因为"leetcode"可以被分割成"leet code".
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".
此题可以用动态规划来做,因为不知道这个单词到底有多少个词组成,所以我们把这个问题化为n个小问题,然后以小问题逐个推导到后面的答案。
class Solution {
public:
bool wordBreak(string s, unordered_set<string> &dict) {
if (s.empty()){
return false;
}
if (dict.empty()){
return false;
}
vector<bool>a(s.size()+1, 0);
a[0] = true;
for (int i = 1; i<s.size()+1; i++){
for (int j = 0; j<i; j++){
if (a[j]){
if (dict.count(s.substr(j, i - j))){
a[i] = true;
break;
}
}
}
}
return a[s.size()];
}
};