LeetCode 刷题【139. 单词拆分】

139. 单词拆分

自己做(超时)

java 复制代码
class Solution {
    private boolean is_exist = false;

    public void searchWord(String s, int begin, List<String> wordDict){
        if(begin == s.length()){
            is_exist = true;
            return;
        }

        for(int i = 0; i < wordDict.size(); i++)
            for(int j = begin; j < s.length() && j - begin + 1 <= wordDict.get(i).length(); j++)
                if(s.substring(begin, j + 1).equals(wordDict.get(i)))
                    searchWord(s, j + 1, wordDict);

    }


    public boolean wordBreak(String s, List<String> wordDict) {
        searchWord(s, 0, wordDict);

        return is_exist;
    }
}

看题解

官方题解

java 复制代码
public class Solution {
    public boolean wordBreak(String s, List<String> wordDict) {
        Set<String> wordDictSet = new HashSet(wordDict);
        boolean[] dp = new boolean[s.length() + 1];
        dp[0] = true;
        for (int i = 1; i <= s.length(); i++) {
            for (int j = 0; j < i; j++) {
                if (dp[j] && wordDictSet.contains(s.substring(j, i))) {
                    dp[i] = true;
                    break;
                }
            }
        }
        return dp[s.length()];
    }
}
相关推荐
Aspect of twilight14 小时前
LeetCode华为2025年秋招AI大模型岗刷题(四)
算法·leetcode·职场和发展
有泽改之_21 小时前
leetcode146、OrderedDict与lru_cache
python·leetcode·链表
im_AMBER21 小时前
Leetcode 74 K 和数对的最大数目
数据结构·笔记·学习·算法·leetcode
无敌最俊朗@21 小时前
STL-vector面试剖析(面试复习4)
java·面试·职场和发展
t1987512821 小时前
电力系统经典节点系统潮流计算MATLAB实现
人工智能·算法·matlab
断剑zou天涯21 小时前
【算法笔记】蓄水池算法
笔记·算法
长安er1 天前
LeetCode 206/92/25 链表翻转问题-“盒子-标签-纸条模型”
java·数据结构·算法·leetcode·链表·链表翻转
Benmao⁢1 天前
C语言期末复习笔记
c语言·开发语言·笔记·leetcode·面试·蓝桥杯
唯道行1 天前
计算机图形学·23 Weiler-Athenton多边形裁剪算法
算法·计算机视觉·几何学·计算机图形学·opengl
CoderYanger1 天前
动态规划算法-01背包问题:50.分割等和子集
java·算法·leetcode·动态规划·1024程序员节