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()];
}
};