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()];
    }
}
相关推荐
地平线开发者15 分钟前
征程6工具链模型X86推理方式说明
算法
地平线开发者20 分钟前
【征程6】校准量化中HistogramObserver解析
算法
OuO-21 小时前
笔试强训 Day 34:ISBN 号码、kotori 和迷宫、矩阵最长递增路径
java·算法·矩阵
程序喵大人2 小时前
【C++进阶】STL算法与函数对象 - 04 find、count和any_of把查询写成意图
开发语言·c++·算法
豆沙沙包?2 小时前
c++中引用(P7-P11)
java·c++·算法
不会代码的小猴2 小时前
标准模板库(STL)
开发语言·c++·笔记·算法
ZhouDevin3 小时前
算法论文/高效微调4——DoRA:权重分解的低秩适配方法
算法
evans在进步3 小时前
LeetCode 200:岛屿数量——Java DFS 染色法详解
java·leetcode·深度优先
AI探索先锋3 小时前
A* 路径规划:四种算法的进化史-学习
学习·算法
旖旎夜光3 小时前
LeetCode 202:快乐数(双指针问题) —— 题解
数据结构·c++·算法·leetcode·双指针