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()];
    }
}
相关推荐
夜思红尘6 小时前
算法--双指针
python·算法·剪枝
散峰而望6 小时前
【算法竞赛】C++函数详解:从定义、调用到高级用法
c语言·开发语言·数据结构·c++·算法·github
CoderCodingNo6 小时前
【GESP】C++五级真题(贪心思想考点) luogu-B4071 [GESP202412 五级] 武器强化
开发语言·c++·算法
我有一些感想……6 小时前
An abstract way to solve Luogu P1001
c++·算法·ai·洛谷·mlp
前端小L6 小时前
双指针专题(三):去重的艺术——「三数之和」
javascript·算法·双指针与滑动窗口
在风中的意志7 小时前
[数据库SQL] [leetcode] 2388. 将表中的空值更改为前一个值
数据库·sql·leetcode
智者知已应修善业8 小时前
【求等差数列个数/无序获取最大最小次大次小】2024-3-8
c语言·c++·经验分享·笔记·算法
还不秃顶的计科生8 小时前
LeetCode 热题 100第二题:字母易位词分组python版本
linux·python·leetcode
LYFlied8 小时前
【每日算法】LeetCode 416. 分割等和子集(动态规划)
数据结构·算法·leetcode·职场和发展·动态规划
多米Domi0118 小时前
0x3f 第19天 javase黑马81-87 ,三更1-23 hot100子串
python·算法·leetcode·散列表