[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个字母是否能拆分成单词,状态转移方程是count1[i] = count1[j] &&hashTable.count(s.substr(j,i-j))>0。

相关推荐
近津薪荼12 小时前
优选算法——前缀和(7):连续数组
算法
ArturiaZ12 小时前
【day29】
数据结构·c++·算法
MoonOutCloudBack12 小时前
VeRL 框架下 RL 微调 DeepSeek-7B,比较 PPO / GRPO 脚本的参数差异
人工智能·深度学习·算法·语言模型·自然语言处理
_F_y13 小时前
二叉树中的深搜
算法
锅包一切13 小时前
PART17 一维动态规划
c++·学习·算法·leetcode·动态规划·力扣·刷题
Polaris北13 小时前
第二十六天打卡
c++·算法·动态规划
罗湖老棍子15 小时前
【例 2】选课(信息学奥赛一本通- P1576)
算法·树上背包·树型动态规划
每天要多喝水15 小时前
动态规划Day33:编辑距离
算法·动态规划
每天要多喝水15 小时前
动态规划Day34:回文
算法·动态规划
weixin_4772716915 小时前
马王堆帛书《周易》系统性解读(《函谷门》原创)
算法·图搜索算法