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

相关推荐
玖剹1 分钟前
哈希表相关题目
数据结构·c++·算法·leetcode·哈希算法·散列表
laocooon52385788613 分钟前
相对名次算法的处理python
开发语言·python·算法
lixinnnn.26 分钟前
bfs: kotori和迷宫
算法·宽度优先
暗然而日章29 分钟前
C++基础:Stanford CS106L学习笔记 14 类型安全 & `std::optional`
c++·笔记·学习
L_090731 分钟前
【C++】高阶数据结构 -- 二叉搜索树(BST)
数据结构·c++
大筒木老辈子33 分钟前
C++笔记---并发支持库(future)
java·c++·笔记
PyGata1 小时前
CMake学习笔记(二):CMake拷贝文件夹
c++·笔记·学习
Felven1 小时前
A. Shizuku Hoshikawa and Farm Legs
算法
仰泳的熊猫1 小时前
1150 Travelling Salesman Problem
数据结构·c++·算法·pat考试
练习时长一年1 小时前
LeetCode热题100(最小栈)
java·算法·leetcode