-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathleetCode_140.java
More file actions
44 lines (34 loc) · 1.17 KB
/
Copy pathleetCode_140.java
File metadata and controls
44 lines (34 loc) · 1.17 KB
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
class Solution {
HashSet<String> set = new HashSet<>();
boolean[] dp;
private final Map<String, List<String>> cache = new HashMap<>();
public List<String> wordBreak(String s, List<String> wordDict) {
dp = new boolean[s.length()+1];
dp[0] = true;
for(String ss: wordDict){
set.add(ss);
}
return backTrack(s);
}
private boolean containsSuffix( String str) {
for (int i = 0; i < str.length(); i++) {
if (set.contains(str.substring(i))) return true;
}
return false;
}
List<String> backTrack(String s){
if(cache.containsKey(s)) return cache.get(s);
List<String> result = new ArrayList<>();
if (set.contains(s)) result.add(s);
for(int i= 1; i < s.length(); i++){
String left = s.substring(0, i) , right = s.substring(i);
if(set.contains(left) && containsSuffix(right)){
for(String ss: backTrack(right)){
result.add(left + " " + ss);
}
}
}
cache.put(s, result);
return result;
}
}