Leetcode(139)单词的拆--动态规划做法

Leetcode(139)单词的拆分–动态规划做法

先介绍一下语法

#include <iostream>
using namespace std;
#include <vector>
#include <string>

int main() {
    vector<string> s={"leetcode","words","dogs"};
    for(auto&word:s)
    {
        cout<<word;
        cout<<word.size()<<endl;
    }

}

  //

在这里插入图片描述
运行结果

for(auto&word:string){}是一种类似pyhton的写法。

在这里插入图片描述
在这里插入图片描述

class Solution {
public:
    bool wordBreak(string& s, vector<string>& wordDict) {
        vector<bool> dp(s.size(), 0);//初始化bool类型的dp数组
        //这里的dp[i]==1代表从(0-i)可以被wordDict中的单词表示出来
        //dp[i]==0 代表没有办法表示出来
        dp[0] = true;//初始化值,可以被表示出来

        for(int i = 0; i < s.size(); i++){//循环从0到size-1
            if(dp[i]==0)//说明此时的字串没有办法被表示出来,直接跳过后面
                continue;
            for(auto& word : wordDict)//循环wordDict中的每个单词
                if(s.substr(i, word.size()) == word)
                    //如果(i,i+word.size)可以匹配上
                    dp[i+word.size()] = true;//将此处标记为true;
            
            if(dp[s.size()]==1)//如果标记到最后一个,那么直接跳出循环返回真值就可以
                break;
        }
        return dp[s.size()];
    }
};
  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值