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

相关推荐
_wyt0011 小时前
多重背包问题详解
c++·背包dp
Ljwuhe2 小时前
C++——多态
开发语言·c++
越甲八千2 小时前
STL stack为何没有迭代器
c++
CV-Climber2 小时前
检索技术的实际应用
人工智能·算法
hhzz3 小时前
Tiger AI Platform平台中增加人脸识别功能
图像处理·人工智能·算法·计算机视觉·大模型
从零开始的代码生活_4 小时前
C++ 继承详解:访问控制、对象模型、菱形继承与设计取舍
开发语言·c++·后端·学习·算法
云小逸4 小时前
【C++ 第七阶段:模板、泛型编程与工程综合详解】
开发语言·c++
TsingtaoAI4 小时前
3D高斯泼溅技术发展及其在具身智能领域的应用综述
人工智能·算法·ai·具身智能·高斯泼溅
atunet4 小时前
关于图算法中的连通分量检测与最小割问题7
算法