当前位置:网站首页>头脑风暴:单词拆分
头脑风暴:单词拆分
2022-08-09 23:53:00 【InfoQ】
题目
输入: s = "leetcode", wordDict = ["leet", "code"]
输出: true
解释: 返回 true 因为 "leetcode" 可以由 "leet" 和 "code" 拼接成。
输入: s = "applepenapple", wordDict = ["apple", "pen"]
输出: true
解释: 返回 true 因为 "applepenapple" 可以由 "apple" "pen" "apple" 拼接成。
注意,你可以重复使用字典中的单词。
输入: s = "catsandog", wordDict = ["cats", "dog", "sand", "and", "cat"]
输出: false
解题方法
代码实现
class Solution {
public boolean wordBreak(String s, List<String> wordDict) {
Set<String> wordDictSet = new HashSet(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(dp[j] && wordDictSet.contains(s.substring(j, i))){
dp[i] = true;
break;
}
}
}
return dp[s.length()];
}
}
最后
- 时间复杂度:O(n^2),其中 nn 为字符串 s 的长度。我们一共有 O(n) 个状态需要计算,每次计算需要枚举 O(n) 个分割点,哈希表判断一个字符串是否出现在给定的字符串列表需要 O(1) 的时间,因此总时间复杂度为 O(n^2)。
- 空间复杂度:O(n),其中 n 为字符串 s 的长度。
边栏推荐
猜你喜欢

【CAS:41994-02-9 |Biotinyl tyramide】生物素基酪氨酰胺价格

生物素叠氮化物中的(CAS:1527486-16-3TAMRA-azide-PEG3-Biotin)反应的特点!

字节技术面都过了,薪资都谈好了20K*13结果还是被刷了,问HR原因是。。。

【毕业设计】 基于Stm32的家庭智能监控系统 - 单片机 图像识别 人体检测 AI

The older tester has just passed the "hurdle" of being 35 years old, and I want to tell you something from my heart

D-Biotinol Involved by Biotin, CAS No: 53906-36-8 Specific Properties Description

Creo5.0入门教程赠素材

Why don't suggest you run in Docker Mysql?

足不出户也能看星空

Leecode-205. 同构字符串
随机推荐
arm-4-裸板开发
关于HBuilder X鼠标变为_ 替换字符的问题
2022金九银十工作潮,怎么样才能成功跳槽面试拿到高薪呢?
共创 Ray 中文社区,Ray Forward Meetup 2022 直播邀你参加!
Win7怎么把控制面板添加到右键菜单
2022中高级Android面试题汇总来助你通过面试
Leetcode82. 删除排序链表中的重复元素 II
ETCD快速入门-02 ETCD安装
NTP SERVICE TASK 在GWserver配置、启用NTP服务,为当前环境提供时钟同步服务,Client主机可以从该服务器同步时间。
Copper's emotion
JVM Memory and Garbage Collection - 10. Direct Memory
【毕业设计】 基于Stm32的家庭智能监控系统 - 单片机 图像识别 人体检测 AI
How to activate the payment function on WeChat official account?
Characteristics of the (CAS:1527486-16-3TAMRA-azide-PEG3-Biotin) reaction in biotin azide!
最高月薪15K,谁有历经千辛万苦的意志,谁就能收获属于自己的成功~
MATLB|和她跌宕起伏最终到达人生之峰【浪漫旅途】
EL表达式
-红与黑-
基于ABP的AppUser对象扩展
-Knight Parade-