当前位置:网站首页>LeetCode_139_word split
LeetCode_139_word split
2022-08-02 12:32: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 <= 300
1 <= wordDict.length <= 1000
1 <= wordDict[i].length <= 20
s
和wordDict[i]
仅有小写英文字母组成wordDict
中的所有字符串 互不相同
解题思路
动态规划五部曲
确定
dp
数组及下标的含义dp[i]
:字符串长度为i
,dp[i] = true
,it means that it can be divided into one or more words that appear in the dictionary
确定递推公式
- 如果
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()];
}
}
边栏推荐
猜你喜欢
FreeRTOS experiment--one function creates multiple tasks
不错的射击类js小游戏源码
After Effects 教程,如何在 After Effects 中对蒙版进行动画绘制?
Likou 977-Squaring of ordered arrays - brute force method & double pointer method
Do you really understand the business process service BPass?
FreeRTOS--栈实验
Process finished with exit code 1
Likou 704 - binary search
手撸架构,MongDB 面试50问
力扣151-颠倒字符串中的单词
随机推荐
DTG-SSOD:最新半监督检测框架,Dense Teacher(附论文下载)
力扣35-搜索插入位置——二分查找
#Summer Challenge#[FFH] OpenHarmony Device Development Foundation (3) Compilation Dependencies
数据湖(三):Hudi概念术语
Distributed current limiting, hand & redisson implementation
力扣704-二分查找
前男友买辣椒水威胁要抢女儿,女方能否申请人身安全保护令?
测试开发之路,我在大厂做测试这四年的感悟
The 7 most commonly used data analysis thinking, solve 95% of the analysis problems
【The 6th Strong Net Cup CTF-Wp】
JVM学习----垃圾回收调优
Thymeleaf
openresty 性能优化
手撸架构,网络 面试36问
Golang map数组按字段分类
力扣58-左旋转字符串
一款强大的js弹出alert插件
MD5 detailed explanation (check file integrity)
解决导出excel文件名中文乱码的问题
The use of QListView