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()];
    }
}
相关推荐
m0_736927047 小时前
使用 Python 将 PowerPoint 转换为 Word 文档
java·开发语言·后端·职场和发展·c#
夜晚中的人海7 小时前
【C++】位运算算法习题
开发语言·c++·算法
superior tigre8 小时前
(huawei)5.最长回文子串
c++·算法
OG one.Z8 小时前
08_集成学习
人工智能·算法·机器学习
CoovallyAIHub8 小时前
超越传统3D生成:OccScene实现感知与生成的跨任务共赢
深度学习·算法·计算机视觉
Mr.H01279 小时前
克鲁斯卡尔(Kruskal)算法
数据结构·算法·图论
Tisfy9 小时前
LeetCode 3346.执行操作后元素的最高频率 I:滑动窗口(正好适合本题数据,II再另某他法)
算法·leetcode·题解·滑动窗口·哈希表
CoovallyAIHub9 小时前
华为世界模型来了!30分钟生成272㎡室内场景,虚拟人导航不迷路
深度学习·算法·计算机视觉
熬了夜的程序员9 小时前
【LeetCode】94. 二叉树的中序遍历
数据结构·算法·leetcode·职场和发展·深度优先