Word Break II

本文详细解析如何使用动态规划算法解决字符串分词问题,包括定义状态转移方程、构建状态矩阵及输出最终结果的过程。通过实例演示,帮助读者理解和掌握动态规划在字符串分词中的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Given a string s and a dictionary of words dict, add spaces in s to construct a sentence where each word is a valid dictionary word.

Return all such possible sentences.

For example, given
s = "catsanddog",
dict = ["cat", "cats", "and", "sand", "dog"].

A solution is ["cats and dog", "cat sand dog"].

其实我觉得这题很难,对于菜鸟来说,也是理解别人的代码理解了两天才弄明白,对于动态规划,一直都不是很会用,这里,把我理解的深入地表示一下。其中,dp[i][j]表示从i到j的字符串是否在字典中。



这是以题目举得一个例子,此张表中的0,1就是dp的表示,红框和绿框表示第一轮和第二轮寻找(从下往上)。具体代码和注释如下,解释很麻烦,希望可以看懂:

class Solution {
public:
vector<bool>*dp;
vector<string>mystring;
vector<string>result;
vector<string> wordBreak(string s, unordered_set<string> &dict){
dp = new vector<bool>[s.size()];  //定义一个二维数组
for (int i = 0;i<s.size();i++)
{
for (int j = i;j<s.size();j++)
{
if (dict.find(s.substr(i,j-i+1))!=dict.end())  //在字典中一次查找此单词是否存在
dp[i].push_back(true);
else
dp[i].push_back(false);
}
}
Output(s.size()-1,s);        //将存在的单词按照句子的形式表示出来,我觉得这才是最难的地方
return result;
}
void Output(int index,string s)
{
if(index == -1)      //如果索引值为-1,也就是说上一个单词已经从0开始了,那么就要组合找到的单词
{
string str;
for (int i = mystring.size()-1;i>=0;i--)  //组合比较简单
{
str += mystring[i];
if (i!=0)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值