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()];
    }
}
相关推荐
海石10 分钟前
1563分的简单题,可能就简单在能被暴力AC
算法·leetcode
海石20 分钟前
1400分的dp汗流浃背之【交替子数组计数】
算法·leetcode
奋发向前wcx24 分钟前
P2590 树的统计 题目解析
数据结构·算法·深度优先
imbackneverdie1 小时前
AI4S不止于分子药物:以MedPeer为代表的科研基建打开产业新增量
大数据·人工智能·算法·aigc·科研·学术·ai 4s
额鹅恶饿呃2 小时前
C语言中的数据结构和变量
c语言·数据结构·算法
运行时记录4 小时前
prompt-optimizer skill
算法
万法若空4 小时前
【数据结构-哈希表】哈希表原理
数据结构·算法·散列表
退休倒计时4 小时前
【每日一题】LeetCode 437. 路径总和 III TypeScript
算法·leetcode·typescript
学逆向的4 小时前
汇编——内存
开发语言·汇编·算法·网络安全
tachibana24 小时前
hot100 翻转二叉树(226)
java·数据结构·算法·leetcode