LeetCode Word Break

本文深入解析Word Break问题的动态规划解法,提供详细题解与代码实现,包括时间复杂度、空间复杂度分析及AC Java版本。同时探讨进阶版Word Break II的相关内容。

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

原题链接在这里:https://leetcode.com/problems/word-break/

题目:

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".

题解:

这是一道DP题,解题思路参考了这篇帖子:http://blog.youkuaiyun.com/linhuanmars/article/details/22358863

 

这道题仍然是动态规划的题目,我们总结一下动态规划题目的基本思路。首先我们要决定要存储什么历史信息以及用什么数据结构来存储信息。然后是最重要的递推式,就是如从存储的历史信息中得到当前步的结果。最后我们需要考虑的就是起始条件的值。

接下来我们套用上面的思路来解这道题。首先我们要存储的历史信息res[i]是表示到s的第i个元素为止能不能用字典中的词来表示,我们需要一个长度为n的布尔数组来存储信息。

然后递推时,假设我们现在拥有res[0,...,i-1]的结果,我们来获得res[i]的值。思路是对于每个以i为结尾的子串,看看是否存在j, j<i, 之前到j时能用字典中的词表示 并且 j到i这段也能在字典中找到. 如果都成立,那么res[i]为true.

Time Complexity: O(s.length() ^ 2). 

Space: O(s.length()).

AC Java:

 1 public class Solution {
 2     public boolean wordBreak(String s, Set<String> wordDict) {
 3         if(s == null || s.length() == 0){
 4             return true;
 5         }
 6         boolean [] res = new boolean[s.length()+1];
 7         res[0] = true;
 8         
 9         for(int i = 1; i<=s.length(); i++){
10             StringBuilder sb = new StringBuilder(s.substring(0,i));
11             for(int j = 0; j<i; j++){
12                 //res[j] 为true 表示s.substring(0,j+1) 能被break.
13                 if(res[j] && wordDict.contains(sb.toString())){
14                     res[i] = true;
15                 }
16                 sb.deleteCharAt(0);
17             }
18         }
19         return res[res.length - 1];
20     }
21 }

这题后面还有一个进阶版本的Word Break II

转载于:https://www.cnblogs.com/Dylan-Java-NYC/p/4824964.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值