解题思路
对于长度为 i 的字符串,当且仅当长度为 j ( j < i )的字符串合法且下标从 i - j 到 i 的字符串能被字典中的任意一词表示时长度为 i 的字符串合法,即
具体步骤如下:
1.首先将字典从查找效率较低的vector容器转移到unordered set中:
unordered_set<string> dict(word_Dict.begin(), word_Dict.end());
2.初始化动态规划数组
int l = s.size();
bool* dp = new bool[l+1]{false};
dp[0] = true;
3.判断长度为i的字符串是否合法(能被拆分成多个单词)
for(int i = 1; i <= l; i++)
{
for(int j = 0; j < i; j++)
{
if(dp[j] == false)
continue;
string temp = s.substr(j, i-j);
if(dict.find(temp) != dict.end())
dp[i] = true;
}
}
4.返回答案
bool ans = dp[l];
delete[] dp[l];
return ans;
完整代码
#include <iostream>
#include <vector>
#include <unordered_set>
#include <string>
using namespace std;
class Solution {
public:
bool wordBreak(string s, vector<string>& wordDict)
{
unordered_set<string> dict(wordDict.begin(), wordDict.end());
int l = s.size();
bool* dp = new bool[l+1]{false};
dp[0] = true;
for(int i = 1; i <= l; i++)
{
for(int j = 0; j < i; j++)
{
if(dp[j] == false)
continue;
string temp = s.substr(j, i-j);
if(dict.find(temp) != dict.end())
dp[i] = true;
}
}
bool ans = dp[l];
delete[] dp[l];
return ans;
}
};
int main()
{
vector<string> dict = {"leet", "code"};
string s = "leetcode";
Solution sol;
bool ans = sol.wordBreak(s, dict);
cout << ans << endl;
return 0;
}