直接动态规划,之前没有考虑到可能当前位置已经满足,提交之后发现错误。经过打印发现问题,由于当前位置更新可分true和不可分false之后,后来继续分割时可能又不满足了,所以在更新dp[n]的时候应该考虑dp[n]是否为true,因此需要或运算。
ac总消耗:
4ms 7.3MB
本人解答:
#include<string>
#include<vector>
#include<iostream>
using namespace std;
class Solution {
public:
bool wordBreak(string s, vector<string>& wordDict) {
vector<bool>dp(s.length() + 1, false);
dp[0] = true;
for (int n = 0; n <= s.length(); ++n)
{
for (int m = 0; m < wordDict.size(); ++m)
{
//if (n >= wordDict[m].length())
//{
//cout << "berfor is: " << dp[n - wordDict[m].length()] << endl;
//cout<<"substr: "<<s.substr(n - wordDict[m].length(), wordDict[m].length())<<endl;
//cout << "now str: " << wordDict[m] << endl;
//}
if (n >= wordDict[m].length() && (s.substr(n - wordDict[m].length(), wordDict[m].length()) == wordDict[m]))
{
dp[n] =dp[n]||dp[n - wordDict[m].length()]&& s.substr(n - wordDict[m].length(), wordDict[m].length()) == wordDict[m];
}
}
//for (auto d : dp)cout << d << " ";
//cout << endl;
}
return dp[s.length()];
}
};
int main()
{
Solution kill;
string s = "dogs";
vector<string>wordDict{ "dog","s","gs" };
if (kill.wordBreak(s, wordDict))
cout << "Yes" << endl;
else
cout << "No" << endl;
return 0;
}