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()];
    }
}
相关推荐
会编程的土豆23 分钟前
日常做题 vlog
数据结构·c++·算法
Omigeq1 小时前
1.4 - 曲线生成轨迹优化算法(以BSpline和ReedsShepp为例) - Python运动规划库教程(Python Motion Planning)
开发语言·人工智能·python·算法·机器人
网络工程小王1 小时前
【大模型(LLM)的业务开发】学习笔记
人工智能·算法·机器学习
y = xⁿ1 小时前
【Leet Code 】滑动窗口
java·算法·leetcode
WBluuue1 小时前
数据结构与算法:二项式定理和二项式反演
c++·算法
nianniannnn1 小时前
力扣104.二叉树的最大深度 110. 平衡二叉树
算法·leetcode·深度优先
_深海凉_1 小时前
LeetCode热题100-只出现一次的数字
算法·leetcode·职场和发展
nianniannnn2 小时前
力扣206.反转链表 92.反转链表II
算法·leetcode·链表
澈2072 小时前
哈希表实战:从原理到手写实现
算法·哈希算法
旖-旎2 小时前
哈希表(存在重复元素||)(4)
数据结构·c++·算法·leetcode·哈希算法·散列表