C语言 | Leetcode C语言题解之第139题单词拆分

题目:

题解:

cpp 复制代码
unsigned long long Hash(char* s, int l, int r) {
    unsigned long long value = 0;
    for (int i = l; i < r; i++) {
        value = value * 2333ull;
        value += s[i] - 'a' + 1;
    }
    return value;
}
bool query(unsigned long long* rec, int len_rec, unsigned long long x) {
    for (int i = 0; i < len_rec; i++) {
        if (rec[i] == x) return true;
    }
    return false;
}
bool wordBreak(char* s, char** wordDict, int wordDictSize) {
    unsigned long long rec[wordDictSize + 1];
    for (int i = 0; i < wordDictSize; i++) {
        rec[i] = Hash(wordDict[i], 0, strlen(wordDict[i]));
    }
    int len_s = strlen(s);
    bool dp[len_s + 1];
    memset(dp, 0, sizeof(dp));
    dp[0] = true;
    for (int i = 1; i <= len_s; i++) {
        for (int j = 0; j < i; j++) {
            if (dp[j] && query(rec, wordDictSize, Hash(s, j, i))) {
                dp[i] = true;
                break;
            }
        }
    }
    return dp[len_s];
}
相关推荐
haolin123.42 分钟前
类和对象(下)
c语言·开发语言·c++
皓月斯语1 小时前
P5736 【深基7.例2】质数筛
c++·算法·题解
木井巳3 小时前
【DFS解决floodfill算法】岛屿的最大面积
java·算法·leetcode·深度优先
(Charon)3 小时前
【C++】手写 MySQL 连接池(三):异步任务队列与工作线程
c语言·c++
yyds_yyd_100863 小时前
877. 石子游戏(2026.08.02)& 486. 预测赢家(2026.08.01)
c++·leetcode
加油码4 小时前
共享内存详解:原理、系统调用与高性能进程间通信
linux·c语言·c++
Lzh编程小栈4 小时前
【STM32底层精讲】RCC时钟系统超全详解(时钟树+源码+避坑指南)
c语言·stm32·单片机·嵌入式硬件·面试
普通攻击往后拉14 小时前
Leetcode 206. 反转链表
算法·leetcode·链表
Nebula嵌入式15 小时前
【C语言】09-深入解析main函数
linux·c语言·开发语言·嵌入式
天空'之城17 小时前
C 语言工业级通用组件手写 23:卡尔曼滤波(简易版)
c语言·卡尔曼滤波·嵌入式算法·工业级组件