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

相关推荐
卷无止境12 小时前
Eigen 库如何借助 OpenMP 加速计算
c++·后端
_清歌12 小时前
DSpark 深度解读:DeepSeek-V4 如何用「半自回归」把推理速度提升 85%
算法
统计实现局12 小时前
SVD 的三步走:双对角化、Givens 收敛、排序
算法
躬行见万象12 小时前
《VLA 系列》UniLab 强化训练 | G1 机器人 |复现
算法
统计实现局12 小时前
对称不定分解(Bunch-Kaufman):为什么 Cholesky 不够用
算法
统计实现局12 小时前
dqrsl 拆解:拿着 QR 结果能算出哪 5 种东西
算法
卷无止境12 小时前
OpenMPI、MPICH 与 OpenMP:关系、核心概念与架构全解
c++·后端
统计实现局12 小时前
为什么 Cholesky 求逆比 Gauss-Jordan 快一倍——行列式溢出防护详
算法
To_OC1 天前
LC 994 腐烂的橘子:人人都说是 BFS 入门题,我却写了三遍才过
javascript·算法·leetcode