

LeetCode 第 139 号问题:单词拆分
source link: https://www.cxyxiaowu.com/6896.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

本文首发于公众号「五分钟学算法」,是图解 LeetCode 系列文章之一。
题目来源于 LeetCode 上第 139 号问题:单词拆分。
给定一个非空字符串 s 和一个包含非空单词列表的字典 wordDict,判定 s 是否可以被空格拆分为一个或多个在字典中出现的单词。
说明:
- 拆分时可以重复使用字典中的单词。
- 你可以假设字典中没有重复的单词。
与 分割回文串 有些类似,都是拆分,但是如果此题采取 深度优先搜索 的方法来解决的话,答案是超时的,不信的同学可以试一下~
为什么会超时呢?
因为使用 深度优先搜索 会重复的计算了有些位的可拆分情况,这种情况的优化肯定是需要 动态规划 来处理的。
如果不知道动态规划的,可以看一下小吴之前的万字长文,比较详细的介绍了动态规划的概念。
在这里,只需要去定义一个数组 boolean[] memo,其中第 i 位 memo[i] 表示待拆分字符串从第 0 位到第 i-1 位是否可以被成功地拆分。
然后分别计算每一位是否可以被成功地拆分。
class Solution {
public boolean wordBreak(String s, List<String> wordDict) {
int n = s.length();
int max_length=0;
for(String temp:wordDict){
max_length = temp.length() > max_length ? temp.length() : max_length;
}
// memo[i] 表示 s 中以 i - 1 结尾的字符串是否可被 wordDict 拆分
boolean[] memo = new boolean[n + 1];
memo[0] = true;
for (int i = 1; i <= n; i++) {
for (int j = i-1; j >= 0 && max_length >= i - j; j--) {
if (memo[j] && wordDict.contains(s.substring(j, i))) {
memo[i] = true;
break;
}
}
}
return memo[n];
}
}
Recommend
-
7
leetcode 30. 串联所有单词的子串 ...
-
4
LeetCode-290-单词规律发布于 9 月 26 日题目描述:给定一种规律 pattern 和一个字符串 str ,判断 str 是否遵循相同的规律。这里的 遵循 指完...
-
7
LeetCode-434-字符串中的单词数发布于 10 月 10 日字符串中的单词数题目描述:统计字符串中的单词个数,这里的单词指的是连续的不是空格的字...
-
1
LeetCode-079-单词搜索发布于 今天 12:40 题目描述:给定一个 m x n 二维字符网格 board 和一个字符串单词 word 。如果 word 存在于网格中,返回 true...
-
8
leetcode 140. 单词拆分 II 发表于...
-
8
#yyds干货盘点# leetcode算法题:串联所有单词的子串 原创 灰太狼_cxh 20...
-
4
#yyds干货盘点# leetcode算法题:最后一个单词的长度 原创 灰太狼_cxh 20...
-
6
#yyds干货盘点# leetcode算法题:连接两字母单词得到的最长回文串 精选 原创 灰太狼_cxh...
-
7
#yyds干货盘点# LeetCode 热题 HOT 100:单词搜索 精选 原创 灰太狼_cxh 2022-10-...
-
2
#yyds干货盘点# LeetCode 热题 HOT 100:单词拆分 精选 原创 灰太狼_cxh 2022-10-...
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK