当前位置:网站首页>LeetCode_139_单词拆分
LeetCode_139_单词拆分
2022-08-02 12:23:00 【Fitz1318】
题目链接
题目描述
给你一个字符串s 和一个字符串列表 wordDict 作为字典。请你判断是否可以利用字典中出现的单词拼接出 s 。
注意:不要求字典中出现的单词全部都使用,并且字典中的单词可以重复使用。
示例 1:
输入: s = "leetcode", wordDict = ["leet", "code"]
输出: true
解释: 返回 true 因为 "leetcode" 可以由 "leet" 和 "code" 拼接成。
示例 2:
输入: s = "applepenapple", wordDict = ["apple", "pen"]
输出: true
解释: 返回 true 因为 "applepenapple" 可以由 "apple" "pen" "apple" 拼接成。
注意,你可以重复使用字典中的单词。
示例 3:
输入: s = "catsandog", wordDict = ["cats", "dog", "sand", "and", "cat"]
输出: false
提示:
1 <= s.length <= 3001 <= wordDict.length <= 10001 <= wordDict[i].length <= 20s和wordDict[i]仅有小写英文字母组成wordDict中的所有字符串 互不相同
解题思路
动态规划五部曲
确定
dp数组及下标的含义dp[i]:字符串长度为i,dp[i] = true,则表示可以采用还分为一个或多个在字典中出现的单词
确定递推公式
- 如果
dp[i] = true,且[i,j]这个区间的子串出现在字典里,那么dp[j] = true
- 如果
数组初始化
dp[0] = true- 其他初始化为
false
确定遍历顺序
- 外层for循环遍历物品,内层for循环遍历背包
举例推导
dp[i]
AC代码
class Solution {
public boolean wordBreak(String s, List<String> 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 (wordDict.contains(s.substring(j, i)) && dp[j]) {
dp[i] = true;
}
}
}
return dp[s.length()];
}
}
边栏推荐
- Drools(8): WorkBench uses
- Metaverse "Drummer" Unity: Crazy expansion, suspense still exists
- 内存存储结构
- Manual architecture, Mysql interview 126 questions
- jvmxmx和xms参数分析(设定优化校准)
- WPF——自定义日历
- 手撸架构,Redis面试41问
- 前男友买辣椒水威胁要抢女儿,女方能否申请人身安全保护令?
- np.nan, np.isnan, None, pd.isnull, pd.isna finishing and summary
- simulink PID auto-tuning
猜你喜欢

MD5 detailed explanation (check file integrity)

AQS-AbstractQueuedSynchronizer

【第六届强网杯CTF-Wp】

力扣35-搜索插入位置——二分查找

The use of QListView

php——三篇夯实根基第一篇

Taurus.MVC V3.0.3 Microservice Open Source Framework Released: Make the evolution of .NET architecture easier in large concurrency.

linux basic command explanation

#夏日挑战赛#【FFH】OpenHarmony设备开发基础(三)编译依赖

看我如何用多线程,帮助运营小姐姐解决数据校对系统变慢!
随机推荐
After Effects 教程,如何在 After Effects 中对蒙版进行动画绘制?
数据湖(三):Hudi概念术语
Chapter 14 Manually create a REST service (2)
An example of type3 voltage loop compensator taking Boost as an example
How to set up wireless PPI communication between Weiluntong touch screen and S7-200smart?
干测试这些年,去过阿里也去过小公司,给年轻测试员们一个忠告...
php字符串的截取方式
excel 批量翻译-excel 批量函数公司翻译大全免费
观察者(observer)模式(二) —— 实现线程安全的监听器
如何通过DBeaver 连接 TDengine?
Likou 704 - binary search
借小程序容器打造自有App小程序生态
Likou 35 - search for insertion position - binary search
Chapter 11 Documents
How to better assess credit risk?Just watch this scorecard model live
unique in numpy & pandas
Solve the problem of Chinese garbled characters in exporting excel file names
Do you really understand the business process service BPass?
喜迎八一 《社会企业开展应聘文职人员培训规范》团体标准出版发行会暨橄榄枝大课堂上线发布会在北京举行
AQS-AbstractQueuedSynchronizer