[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。

相关推荐
2601_9622186123 分钟前
C语言中三种库的编译和使用方法
开发语言·c++
jimy136 分钟前
派生类重写基类虚函数(二):override的作用
开发语言·c++
ebiobiz1 小时前
基于 GD32 Embedded Builder (GEB) 与 Nimmake 的 MCU 工程搭建指南
c++·python·单片机·嵌入式硬件·mcu
hetao17338371 小时前
2026-09-29 hetao1733837 的刷题记录
c++·算法
:mnong1 小时前
几何内核“四大金刚“:ACIS、Parasolid、CGM、Open CASCADE 核心特征深度解析
c++·cad·cax
by209992 小时前
从 malloc/free 到 new/delete:真正理解 C++ 中的内存管理与对象生命周期
c语言·c++·经验分享·动态内存管理
欣欣之王来了2 小时前
AI合规专项:AI算法透明度的合规要求
人工智能·算法
wzdark2 小时前
分块思想在算法优化中的实践与应用4
算法
Because_of_Her12 小时前
dfs-洪水填充技巧
笔记·算法·深度优先·洪水填充
m0_380743872 小时前
Qt侧边栏布局的实现示例
开发语言·c++