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"
.
此题可以用动态规划解决,思路如下: 将一个字符串从前往后切割,发现后边的正好是包含在字典中并且前边的正好可以被切分的话就此串可以被切分,
abcsd
可以分成以下几种情况讨论
1.d是否包含在字典中以及abcsd是否可以被切分
2.sd是否包含在字典中以及abs是否可以被切分
3.csd是否包含在字典中以及ab是否可以被切分
4.bcsd是否包含在字典中以及a是否可以被切分
5.abcsd是否包含在字典中
class Solution {
public:
bool wordBreak(string s, unordered_set<string> &dict) {
vector<bool> wordB(s.length()+1,false);
wordB[0]=true;
for(int i=1;i<=s.length();i++)
{
for(int j=i-1;j>=0;j--)
{
if(wordB[j]&&dict.find(s.substr(j,i-j))!=dict.end())
{
wordB[i]=true;
break;
}
}
}
return wordB[s.length()];
}
};