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

相关推荐
hPw0eKIqD7 小时前
C++ 模板参数推导问题小记(非推导上下文)
开发语言·c++
程序员爱德华7 小时前
Python与C++:异同点对比
c++·python
普通攻击往后拉7 小时前
Leetcode 206. 反转链表
算法·leetcode·链表
@syh.8 小时前
【贪心】矩阵消除游戏
算法·游戏·矩阵
可编程芯片开发8 小时前
基于零极点配置的PID控制系统simulink建模与仿真
算法
徐小夕9 小时前
开源!我用SQLite + DuckDB打造了一款可视化AI问数平台
前端·算法·github
Hrain-AI9 小时前
2026 企业 AI 智能体平台横评:8 大主流平台 7 维度实测对比
人工智能·算法·机器学习
Angel Q.10 小时前
因子分析和生成模型有什么关系?从“幕后因素”到“生成数据”
算法
888CC++10 小时前
C语言与C++的区别:从面向过程到面向对象
java·c语言·c++