给你一个字符串 s
和一个字符串列表 wordDict
作为字典。请你判断是否可以利用字典中出现的单词拼接出 s
。
注意:不要求字典中出现的单词全部都使用,并且字典中的单词可以重复使用。
class Solution {
public:
bool wordBreak(string s, vector<string>& wordDict) {
int l = s.size();
vector<bool> dp(l+1,false);
dp[0] = true;
for(int i = 0;i<l;i++)
{
for(int j = 1;j<=l-i;j++)
{
string str = s.substr(i,j);
if(count(wordDict.begin(),wordDict.end(),str) && dp[i] == true)
dp[i+j] = true;
}
}
return dp[l];
}
};