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];
}
相关推荐
Tisfy1 小时前
LeetCode 0453.最小操作次数使数组元素相等:两次遍历(反向思维)
算法·leetcode·题解·遍历·反向思维
孤独的Bochi1 小时前
# [CSP-S 2026] 迁徙 / migrate 题解
题解
君万1 小时前
【LeetCode每日一题】回溯:46. 全排列 78. 子集 39. 组合总和
算法·leetcode·go
Tisfy3 小时前
LeetCode 3665.统计镜子反射路径数目:三个动态规划数组
leetcode·动态规划·代理模式·题解
海绵宝宝转agent4 小时前
LeetCode100 二叉树个人题解
算法·leetcode·深度优先
文丑颜不良啊5 小时前
LeetCode1581~1600题目解析
java·leetcode
文丑颜不良啊8 小时前
LeetCode1541~1560题目解析
java·leetcode
漂流瓶jz18 小时前
UVA-1612 猜名次 题解答案代码 算法竞赛入门经典第二版
数据结构·算法·题解·排序·aoapc·算法竞赛入门经典
文丑颜不良啊18 小时前
LeetCode1481~1500题目解析
java·leetcode
文丑颜不良啊19 小时前
LeetCode1381~1400题目解析
java·leetcode