当前位置:网站首页>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 <= 300
1 <= wordDict.length <= 1000
1 <= wordDict[i].length <= 20
s
和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()];
}
}
边栏推荐
猜你喜欢
随机推荐
1.3快速生成树协议RSTP
Intelligent Image Analysis-Intelligent Home Appliance Image Target Detection Statistical Counting Detection and Recognition-iCREDIT
PHP伪协议详解
Drools(8):WorkBench使用
数据湖(二):什么是Hudi
How to better assess credit risk?Just watch this scorecard model live
The 7 most commonly used data analysis thinking, solve 95% of the analysis problems
Likou 209 - String with the Minimum Length - Sliding Window Method
excel 批量翻译-excel 批量函数公司翻译大全免费
Pytorch 占用cpu资源过多
1.3 Rapid Spanning Tree Protocol RSTP
7种最常用数据分析思维,解决95%的分析难题
软件成分分析:手握5大能力守护软件供应链安全
According to the field classification Golang map array
Process finished with exit code 1
Likou 704 - binary search
Problem solving in the process of using mosquitto
如何搭建威纶通触摸屏与S7-200smart之间无线PPI通信?
Manual architecture, Mysql interview 126 questions
商业流程服务BPass你真的了解吗?