class Solution {
public List<String> wordBreak(String s, List<String> wordDict) {
List<String> res = new ArrayList<>();
int max = 0, min = Integer.MAX_VALUE;
Set<String> set = new HashSet<>();
for (String word : wordDict) {
set.add(word);
max = Integer.max(max, word.length());
min = Integer.min(min, word.length());
}
boolean f[] = new boolean[s.length() + 1];
f[0] = true;
for (int i = 1; i < s.length() + 1; i++) {
for (int j = Math.max(i - max, 0); j <= i - min; j++) {
if (f[j] && set.contains(s.substring(j, i))) {
f[i] = true;
break;
}
}
}
if (f[s.length()]) {
dfs(s, res, new StringBuilder(), set, 0, max, min);
}
return res;
}
private void dfs(String s, List<String> res, StringBuilder sb, Set<String> set, int index, int max, int min) {
if (index == s.length()) {
sb.deleteCharAt(sb.length() - 1);
res.add(sb.toString());
return;
}
String str;
int size;
for (int i = index + min; i <= s.length() && i <= index + max; i++) {
if (set.contains(str = s.substring(index, i))) {
size = sb.length();
sb.append(str).append(' ');
dfs(s, res, sb, set, i, max, min);
sb.delete(size, sb.length());
}
}
}
}
Java实现 LeetCode 140 单词拆分II
2023-09-14 08:58:08 时间
相关文章
- Java实现 LeetCode 832 翻转图像(位运算)
- Java实现 LeetCode 791 自定义字符串排序(桶排序)
- Java实现 LeetCode 731 我的日程安排表 II(二叉树)
- Java实现 LeetCode 709 转换成小写字母(ASCII码处理)
- Java实现 LeetCode 654 最大二叉树(递归)
- Java实现 LeetCode 646 最长数对链(暴力)
- Java实现 LeetCode 638 大礼包(阅读理解题,DFS)
- Java实现 LeetCode 599 两个列表的最小索引总和(使用hash提高效率)
- Java实现 LeetCode 564 寻找最近的回文数(今天要GG在这道题了 头晕+题难(((φ(◎ロ◎;)φ))))...
- Java实现 LeetCode 532 数组中的K-diff数对(双指针,滑动窗口)
- Java实现 LeetCode 508 出现次数最多的子树元素和
- Java实现 LeetCode 493 翻转对
- Java实现 LeetCode 479 最大回文数乘积
- Java实现 LeetCode 481 神奇字符串
- Java实现 LeetCode 456 132模式
- Java实现 LeetCode 414 第三大的数
- Java实现 LeetCode 413 等差数列划分
- Java实现 LeetCode 392 判断子序列
- Java实现 LeetCode 388 文件的最长绝对路径
- Java实现 LeetCode 299 猜数字游戏
- Java实现 LeetCode 295 数据流的中位数
- Java实现 LeetCode 208 实现 Trie (前缀树)
- Java实现 LeetCode 164 最大间距
- Java实现 LeetCode 112 路径总和
- Java实现 LeetCode 102 二叉树的层次遍历
- Java实现 LeetCode 86 分割链表
- Java实现 LeetCode 38 外观数列
- Java实现 LeetCode 14 最长公共前缀
- Java实现 LeetCode 7整数反转
- Java实现LeetCode_0026_RemoveDuplicatesFromSortedArray
- Java安装手册