forked from fishercoder1534/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path_140.java
49 lines (39 loc) · 1.28 KB
/
_140.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
package com.fishercoder.solutions;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
/**
* 140. Word Break II
*
* Given a string s and a dictionary of words dict, add spaces in s to construct a sentence where each word is a valid dictionary word.
Return all such possible sentences.
For example, given
s = "catsanddog",
dict = ["cat", "cats", "and", "sand", "dog"].
A solution is ["cats and dog", "cat sand dog"].
*/
public class _140 {
public List<String> wordBreak(String s, List<String> wordDict) {
return dfs(s, wordDict, new HashMap<>());
}
List<String> dfs(String s, List<String> wordDict, HashMap<String, List<String>> map) {
if (map.containsKey(s)) {
return map.get(s);
}
ArrayList<String> result = new ArrayList<>();
if (s.length() == 0) {
result.add("");
return result;
}
for (String word : wordDict) {
if (s.startsWith(word)) {
List<String> subList = dfs(s.substring(word.length()), wordDict, map);
for (String sub : subList) {
result.add(word + (sub.length() == 0 ? "" : " ") + sub);
}
}
}
map.put(s, result);
return result;
}
}