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 已用,感觉良好,注意词的边界。
dp这个东西么,如果不主动去想,是想不出来的……
class Solution {
public:
bool wordBreak(string s, unordered_set<string> &dict) {
int n =s.size();
vector<bool> bo(n,0);
if(dict.find(s.substr(0,1))!=dict.end())bo[0]=1;
//bo[0] = 1;
for(int i = 1 ; i <= s.size() ; i++)
{
if(dict.find(s.substr(0,i)) != dict.end())
{
bo[i-1] = 1;
}
}
for(int i = 1 ; i < s.size() ; i++)
{
if(bo[i] == 1)continue;
for(int j = i ; j >= 0 ; j--)
{
if(bo[j] == 1 && dict.find(s.substr(j+1,i-j))!= dict.end())
{
bo[i] =1;
break;
}
if(bo[n-1] == 1)return 1;
}
}
if(bo[n-1] == 1)return 1;
return 0;
}
};