[LeetCode]139.单词拆分(C++)

1.代码

cpp 复制代码
class Solution {
public:
    bool wordBreak(string s, vector<string>& wordDict) {
        int length = s.size();
        bool *count1 = new bool[length+1];
        fill(count1, count1 + length + 1, false);
        unordered_map<string, bool> hashTable;
        count1[0] = true;
        for(int i = 0;i < wordDict.size();i ++){
            hashTable[wordDict[i]] = true;
        }
        for(int i = 1;i <= length;i ++){
            for(int j = 0;j < i;j ++){
                if(count1[j] && hashTable.count(s.substr(j,i-j))>0){
                    count1[i] = true;
                    break;
                }
            }
        }
        return count1[length];
    }
};

2.思路

用了动态规划,用一个count1数组记录字符串的前i个字母是否能拆分成单词,状态转移方程是count1i = count1j &&hashTable.count(s.substr(j,i-j))>0。

相关推荐
罗湖老棍子10 小时前
【例 1】Sightseeing Trip(信息学奥赛一本通- P1494)(洛谷-P10927)
数据结构·算法·图论·最短路·floyd·最小环
文丑颜不良啊11 小时前
LeetCode201~225题目解析
java·leetcode
努力实干11 小时前
面向对象设计原则——C++
开发语言·c++·数码相机
stsdddd13 小时前
YOLO算法建筑工地安全帽目标检测数据集16881张:标注核对笔记
算法·yolo·目标检测
CV爱数码13 小时前
论文精读|Learned Primal-Dual:把原始–对偶算法展开成网络
图像处理·算法·计算机视觉·ct·重建·断层扫描
yuniko-n14 小时前
【算法】约瑟夫环问题
java·算法
syagain_zsx14 小时前
jsoncpp 使用指南:编译链接、Json::Value 取值与高频坑
c++·json·库·http格式
l1t14 小时前
测试DuckDB v2.1.0-alpha49002的bignum乘法
数据库·sql·算法·duckdb
Nil20814 小时前
LeetCode 283移动零
数据结构·算法·leetcode
CQU_JIAKE14 小时前
10.18【A】
算法