当前位置:网站首页>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()];
}
}
边栏推荐
- QListView的使用
- 商业流程服务BPass你真的了解吗?
- MySQL主从复制几个重要的启动选项
- MD5 detailed explanation (check file integrity)
- Taurus.MVC V3.0.3 Microservice Open Source Framework Released: Make the evolution of .NET architecture easier in large concurrency.
- liunx基础命令讲解
- 数据湖(一):数据湖概念
- np.nan, np.isnan, None, pd.isnull, pd.isna 整理与小结
- An example of type3 voltage loop compensator taking Boost as an example
- zabbix自动化监控脚本
猜你喜欢
redis cluster cluster, the ultimate solution?

Swiper系列之轮播图

CCF paper conference IEEE how to query all articles of a conference journal

网站自动翻译-网站批量自动翻译-网站免费翻译导出

手撸架构,Mysql 面试126问

免费的中英文翻译软件-自动批量中英文翻译软件推荐大全

力扣27-移除元素——简单题

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

pig4cloud服务架构使用

php——三篇夯实根基第一篇
随机推荐
分布式限流利器,手撕&redisson实现
The 7 most commonly used data analysis thinking, solve 95% of the analysis problems
干测试这些年,去过阿里也去过小公司,给年轻测试员们一个忠告...
darknet训练yolov4模型
php字符串的截取方式
[kali-information collection] (1.9) Metasploit + search engine tool Shodan
How to better assess credit risk?Just watch this scorecard model live
ABAP-OOAVL模板程序
After Effects 教程,如何在 After Effects 中对蒙版进行动画绘制?
MyCat2 introduction and installation and basic use
【MySQL】多表联合查询、连接查询、子查询「建议收藏」
元宇宙“吹鼓手”Unity:疯狂扩局,悬念犹存
Thymeleaf
解决导出excel文件名中文乱码的问题
AQS-AbstractQueuedSynchronizer
观察者(observer)模式(二) —— 实现线程安全的监听器
30行代码实现无服务器实时健康码识别--操作手册
SQL function TRIM
excel 批量翻译-excel 批量函数公司翻译大全免费
Process finished with exit code 1