【LeetCode】 140. Word Break II 单词拆分 II(Hard)(JAVA)
题目地址: https://leetcode.com/problems/word-break-ii/
题目描述:
Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, add spaces in s to construct a sentence where each word is a valid dictionary word. Return all such possible sentences.
Note:
- The same word in the dictionary may be reused multiple times in the segmentation.
- You may assume the dictionary does not contain duplicate words.
Example 1:
Input:
s = "catsanddog"
wordDict = ["cat", "cats", "and", "sand", "dog"]
Output:
[
"cats and dog",
"cat sand dog"
]
Example 2:
Input:
s = "pineapplepenapple"
wordDict = ["apple", "pen", "applepen", "pine", "pineapple"]
Output:
[
"pine apple pen apple",
"pineapple pen apple",
"pine applepen apple"
]
Explanation: Note that you are allowed to reuse a dictionary word.
Example 3:
Input:
s = "catsandog"
wordDict = ["cats", "dog", "sand", "and", "cat"]
Output:
[]
题目大意
给定一个非空字符串 s 和一个包含非空单词列表的字典 wordDict,在字符串中增加空格来构建一个句子,使得句子中所有的单词都在词典中。返回所有这些可能的句子。
说明:
- 分隔时可以重复使用字典中的单词。
- 你可以假设字典中没有重复的单词。
解题方法
暴力解法
- 暴力解法就是通过迭代
- 抽取迭代公共方法:假如 string temp = s.substring(0, k) 在 wordDict 数组里面,下一步要怎么办呢?
- 就当做 s 的前面 k 个元素不存在,从 s 的第 k 个元素开始,重新做一遍 wordBreak 的操作(当然这里要保留前面得到的结果,不是真的重做)
class Solution {
public List<String> wordBreak(String s, List<String> wordDict) {
List<String> res = new ArrayList<>();
wH(res, s, 0, wordDict, "");
return res;
}
public void wH(List<String> res, String s, int index, List<String> words, String cur) {
if (s.length() <= index) {
res.add(cur);
return;
}
for (int i = index + 1; i <= s.length(); i++) {
String temp = s.substring(index, i);
if (!words.contains(temp)) continue;
wH(res, s, i, words, cur.length() == 0 ? temp : (cur + " " + temp));
}
}
}
超出时间限制
暴力解法优化
- 上面的暴力解法存在很多重复操作,所以妥妥的超出时间限制
- 比如 index = k 的地方,可能 a 支遍历过,b 支也要遍历一遍,就会造成 index = k 的地方重复遍历多遍,这就是浪费 (如:0->3->5->7, 0->5->7, 0->4->5->7, 就重复了很多次)
- 用一个 map 存起来,把 index = k 开始的可能答案存到一个 list 里面,就可以避免重复操作
class Solution {
public List<String> wordBreak(String s, List<String> wordDict) {
return wH(s, 0, wordDict, new HashMap<>());
}
public List<String> wH(String s, int index, List<String> words, Map<Integer, List<String>> map) {
List<String> res = new ArrayList<>();
if (index >= s.length()) {
return res;
}
if (map.get(index) != null) return map.get(index);
for (int i = index + 1; i <= s.length(); i++) {
String temp = s.substring(index, i);
if (!words.contains(temp)) continue;
if (i == s.length()) {
res.add(temp);
continue;
}
List<String> next = wH(s, i, words, map);
for (int j = 0; j < next.size(); j++) {
res.add(temp + " " + next.get(j));
}
}
map.put(index, res);
return res;
}
}
执行用时:65 ms, 在所有 Java 提交中击败了 19.00% 的用户
内存消耗:39.3 MB, 在所有 Java 提交中击败了 48.73% 的用户