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

相关推荐
洛水水6 分钟前
【力扣100题】53.最长回文子串
算法·leetcode·职场和发展
jieyucx7 分钟前
Go 语言 sort 包详解:从基础排序到自定义排序(含底层原理+零基础看懂)
算法·golang·排序算法·sort
叁散1 小时前
ESP32 LCD1602显示实验报告
算法
过期动态1 小时前
【LeetCode 热题 100】盛最多水的容器
java·数据结构·spring boot·算法·leetcode·spring cloud·职场和发展
凌波粒1 小时前
LeetCode--700.二叉搜索树中的搜索(二叉树)
算法·leetcode·职场和发展
君为先-bey1 小时前
LeMiCa——基于扩散模型的高效视频生成的词典序最小化路径缓存
python·算法·机器学习·扩散模型
洛水水2 小时前
【力扣100题】58.轮转数组
算法·leetcode
资深流水灯工程师2 小时前
LMS 最小均方算法在 DSP 上的 C 语言实现
算法
风筝在晴天搁浅2 小时前
阿里 LeetCode 876.链表的中间节点
算法·leetcode·链表
玖釉-2 小时前
二叉树展开为链表:从先序遍历到原地指针重排
c++·windows·算法·leetcode·链表