【LeetCode】#140單詞拆分II(Word Break II)
【LeetCode】#140單詞拆分II(Word Break II)
題目描述
給定一個非空字串 s 和一個包含非空單詞列表的字典 wordDict,在字串中增加空格來構建一個句子,使得句子中所有的單詞都在詞典中。返回所有這些可能的句子。
說明:
1.分隔時可以重複使用字典中的單詞。
2.你可以假設字典中沒有重複的單詞。
示例
示例 1:
輸入:
s = “catsanddog”
wordDict = [“cat”, “cats”, “and”, “sand”, “dog”]
輸出:
[
“cats and dog”,
“cat sand dog”
]
示例 2:
輸入:
s = “pineapplepenapple”
wordDict = [“apple”, “pen”, “applepen”, “pine”, “pineapple”]
輸出:
[
“pine apple pen apple”,
“pineapple pen apple”,
“pine applepen apple”
]
解釋: 注意你可以重複使用字典中的單詞。
示例 3:
輸入:
s = “catsandog”
wordDict = [“cats”, “dog”, “sand”, “and”, “cat”]
輸出:
[]
Description
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:
1.The same word in the dictionary may be reused multiple times in the segmentation.
2.You may assume the dictionary does not contain duplicate words.
Example
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:
[]
解法
class Solution {
public List<String> wordBreak(String s, List<String> wordDict) {
return helper(s, wordDict, new HashMap<String, LinkedList<String>>());
}
public List<String> helper(String s, List<String> wordDict, HashMap<String, LinkedList<String>> map){
if (map.containsKey(s))
return map.get(s);
LinkedList<String>res = new LinkedList<String>();
if (s.length() == 0) {
res.add("");
return res;
}
for (String word : wordDict) {
if (s.startsWith(word)) {
List<String>sublist = helper(s.substring(word.length()), wordDict, map);
for (String sub : sublist)
res.add(word + (sub.isEmpty() ? "" : " ") + sub);
}
}
map.put(s, res);
return res;
}
}