139. Word Break

本文介绍了一种高效的算法,用于判断一个字符串是否能被拆分成一个或多个字典中出现的单词序列。通过使用布尔数组记录子串是否匹配,避免了递归导致的时间复杂度过高问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 Given a string s and a dictionary of words dict, determine if s can be segmented into a space-separated sequence of one or more dictionary words.

For example, given
s = "leetcode",
dict = ["leet", "code"].

Return true because "leetcode" can be segmented as "leet code".

Subscribe to see which companies asked this question

看上去符合递归的特点,确实用递归也可以得出正确的结果,但是,超时,转换思路----------牛逼的思路------------循环遍历字符串到目前为止是否匹配。。。。代码如下,注释的部分是递归解法


public class Solution {
    public boolean wordBreak(String s, Set<String> wordDict) {
        // int big = Integer.MIN_VALUE;
        // for(String w : wordDict){
        //     big = big > w.length() ? big : w.length();
        // }
        // return getBreak(s, wordDict,0, big);
        boolean[] matches = new boolean[s.length()+1];
        matches[0] = true;
        for(int i = 1; i <= s.length(); i++){
            for(int j = 0; j < i; j ++){
                if(matches[j] && wordDict.contains(s.substring(j, i))){
                    matches[i] = true;
                    break;
                }
            }
            
        }
        
        return matches[s.length()];
    }
    
    // boolean getBreak(String s, Set<String> wordDict, int start, int big){
    //     boolean result = false;
    //     if(start >= s.length()){
    //         return true;
    //     }else{
    //         for(int i = start + 1; i <= start + 1 + big && i <= s.length(); i++){
    //             if(wordDict.contains(s.substring(start, i))){
    //                 result = getBreak(s, wordDict,i, big);
    //                 if(result){
    //                   return result; 
    //                 }
    //             }
    //         }
    //     }
        
    //     return false;
    // }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值