Leetcode(java)139. Word Break

文章描述了一个编程挑战,要求判断一个给定字符串是否能被字典中的单词序列划分。首先尝试了朴素的递归方法,但由于时间复杂度高导致超时。接着,作者采用动态规划优化解决方案,通过创建一个布尔数组表示字符串的前缀是否可由字典单词表示,从而降低时间复杂度。

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

Q:

Given a string s and a dictionary of strings wordDict, return true if s can be segmented into a space-separated sequence of one or more dictionary words.

Note that the same word in the dictionary may be reused multiple times in the segmentation.

A:

First, I used the naive approach.

I use the every string in wordDict to match the first part of the String s.

if they are equal, it continue to match the remaining part of the String s.

class Solution {
    public boolean wordBreak(String s, List<String> wordDict) {
        if(s.length()==0) return true;
        for(String w:wordDict){
            int n = w.length();
            if(n<= s.length() && w.equals(s.substring(0,n))){
               boolean res = wordBreak(s.substring(n,s.length()), wordDict);
               if(res) return res;
            }
        }
        return false;
    }
}

However, this naive approach exceeds the time limit.

Time: O(n^2)

Then I use Dynamic Programming to solve this problem

initial state f[0] = true

f[i] means substring s[0...i-] matches wordDict

f[i]==true while f[j]==true && s[j...i-1] matches wordDict

class Solution {
    public boolean wordBreak(String s, List<String> wordDict) {
        int n = s.length();
        boolean[] f = new boolean[n+1];

        f[0] = true;

        for(int i=0;i<n;i++){
            if(!f[i]) continue;

            for(String w:wordDict){
                if((i+w.length()<=n) && w.equals(s.substring(i,i+w.length()))){
                    f[i+w.length()] = true;
                }
            }
        }

        return f[n];
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值