当前位置:网站首页>139. 单词拆分
139. 单词拆分
2022-06-23 15:06:00 【zzu菜】
给你一个字符串 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
思考
定义dp数组及其下标的含义
dp[i]:表示wordDict前1-i个字母能否由单词组成
- dp[i] =1 ,代表前1-i个字母可以由单词组成
- dp[i] = 0,反之
初始化dp数组
创建dp[ s.length + 1]数组
令dp[ 0 ] =1;
这里dp[0]是起辅助作用,主要目的为的是让 dp[i-word.lenth] ,其i =word.length时,dp = 1;
状态转移方程
这里如果dp[i-word.length] = 1,并且截下来的词和word相同dp[i]=1
class Solution {
public boolean wordBreak(String s, List<String> wordDict) {
// step 1 创建dp数组
int[] dp=new int[s.length()+1];
// step 2 初始化dp数组
dp[0] =1;
// step 3 完善dp数组
for (int i=1;i<dp.length;i++){
for (String word : wordDict) {
if(i>=word.length()){
if (dp[i-word.length()]==0) continue;
String sub=s.substring(i-word.length(),i);
if(sub.equals(word)) {
dp[i]=1;
break;
}
}
}
}
// step 4 printDp
for (int i = 0; i < dp.length; i++) {
System.out.println("dp "+i+","+dp[i]);
}
if (dp[dp.length-1]==1) return true;
else return false;
}
}
边栏推荐
- Tencent ECS failed to send email
- System design and analysis - Technical Report - a solution for regularly clearing verification code
- golang 重要知识:定时器 timer
- MySQL advanced statement 2
- MySQL日志管理怎么配置
- 看,这就是调制解调原理分析!附仿真文件
- How can genetic testing help patients fight disease?
- PHP指定字段大于100正序排,小于100随机排
- Jsr303 data verification
- [cloud based co creation] how manufacturing enterprises build "barcode factories"
猜你喜欢

SQL注入漏洞(原理篇)

General sequence representation learning in kdd'22 "Ali" recommendation system

golang 重要知识:sync.Once 讲解

golang 重要知识:waitgroup 解析

Summary of operating system underlying knowledge (interview)

5 minutes to quickly launch web applications and APIs (vercel)

直播间源码在开发前期必须做的工作及开发步骤

labelme的JSON文件转成COCO数据集格式

Pop() element in JS

这五年的6个编程感悟!
随机推荐
Half wave loss equal thickness and equal inclination interference
JS垃圾回收
[pyside2] pyside2 window is on the top of Maya (note)
嵌入式软件架构设计-程序分层
WebService接口发布和调用
The "shoulder" of sales and service in the heavy truck industry, Linyi Guangshun deep ploughing product life cycle service
js中的push函数介绍
Raspberry PI installing the wiring pi
MySQL日志管理怎么配置
[cloud based co creation] how manufacturing enterprises build "barcode factories"
golang 重要知识:RWMutex 读写锁分析
直播间源码在开发前期必须做的工作及开发步骤
WebService interface publishing and calling
php 二维数组插入
电子学会图形化一级编程题解析:猫捉老鼠
云上探“店”,云商店全新升级!
Matlab| sparse auxiliary signal denoising and pattern recognition in time series data
Starting from 3, add paging function in the business system
This year's cultural entertainers have turned their sidelines into their main business
看,这就是调制解调原理分析!附仿真文件