?LeetCode刷題實戰(zhàn)140:單詞拆分 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.
題意
示例 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"
]
解釋: 注意你可以重復(fù)使用字典中的單詞。
示例?3:
輸入:
s = "catsandog"
wordDict = ["cats", "dog", "sand", "and", "cat"]
輸出:
[]
解題
public?class?Solution?{
????HashMapList > hashMap = new?HashMap<>();
????public?ListwordBreak(String s, List wordDict) {
????????if(hashMap.containsKey(s)) {
????????????return?hashMap.get(s);
????????}
????????Listlist?= new?ArrayList<>();
????????if(0?== s.length()){
????????????list.add("");
????????????return?list;
????????}
????????for(String str : wordDict){
????????????if(s.startsWith(str)){
????????????????ListsubList = wordBreak(s.substring(str.length()), wordDict);
????????????????for(String sub : subList){
????????????????????list.add(str + (Objects.equals("", sub) ? ""?: " ") + sub);
????????????????}
????????????}
????????}
????????hashMap.put(s, list);
????????return?list;
????}
}
