Dynamic Programming——No.139 Word Break

本文探讨了一个经典的字符串处理问题:如何判断一个字符串是否能被分割为字典中的单词序列。通过动态规划方法,文章详细阐述了如何高效地解决这一问题,并提供了具体的算法实现。

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

Problem:

Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, determine if s can be segmented into a space-separated sequence of one or more dictionary words.

Note:

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

You may assume the dictionary does not contain duplicate words.

Explanation:

判断一个完整的字符串能否分割成给定的字符串集,字符串集中的字符串可以重复使用。

My Thinking:

My Solution:

Optimum Thinking:

我们用dp[i]来表示s的第0-i个字符组成的字符串能被分割成若干个字段,且这些字段都在在字典中。

使用i遍历s中的每个字符,使用j在内循环中从0到i,即j将0-i分割成了0-j和j-i,如果0-j组成的字符串是字典内的且j-i组成的字符串也是字典内的,那么我们就将dp[i]=true,表示0-i可以分割成若干个字典内的字符串(一开始是两个,后面将两个看成一个整体,日后的0-j就是现在的0-i),不断更新dp[i]。

Optimum Solution:

class Solution {
    public boolean wordBreak(String s, List<String> wordDict) {
        boolean[] dp = new boolean[s.length() + 1];      
        dp[0] = true; 
        //Second DP
        for(int i=1; i <= s.length(); i++){
            for(int j=0; j < i; j++){
                if(dp[j] && dict.contains(s.substring(j, i))){
                    dp[i] = true;
                    break;
                }
            }
        }       
        return dp[s.length()]; 
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值