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

相关推荐
嘴贱欠吻!5 小时前
Flutter鸿蒙开发指南(七):轮播图搜索框和导航栏
算法·flutter·图搜索算法
张祥6422889045 小时前
误差理论与测量平差基础笔记十
笔记·算法·机器学习
踩坑记录5 小时前
leetcode hot100 2.两数相加 链表 medium
leetcode·链表
qq_192779876 小时前
C++模块化编程指南
开发语言·c++·算法
代码村新手6 小时前
C++-String
开发语言·c++
cici158748 小时前
大规模MIMO系统中Alamouti预编码的QPSK复用性能MATLAB仿真
算法·matlab·预编码算法
历程里程碑8 小时前
滑动窗口---- 无重复字符的最长子串
java·数据结构·c++·python·算法·leetcode·django
2501_940315269 小时前
航电oj:首字母变大写
开发语言·c++·算法
lhxcc_fly9 小时前
手撕简易版的智能指针
c++·智能指针实现
CodeByV9 小时前
【算法题】多源BFS
算法