- Notifications
You must be signed in to change notification settings - Fork 1.8k
/
Copy pathBB3.java
62 lines (47 loc) · 1.85 KB
/
BB3.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
50
51
52
53
54
55
56
57
58
59
60
61
62
importjava.util.*;
publicclassBB3 {
publicList<String> breakWords(Strings, Set<String> wordDict) {
returnbreakWordsHelper(s, wordDict, newHashMap<String, List<String>>());
}
privateList<String> breakWordsHelper(Strings, Set<String> wordDict, Map<String, List<String>> memo) {
if (memo.containsKey(s)) {
returnmemo.get(s);
}
List<String> result = newArrayList<>();
for (Stringword : wordDict) {
if (s.startsWith(word)) {
List<String> subList = breakWordsHelper(s.substring(word.length()), wordDict, memo);
for (StringsubListWord : subList) {
result.add(subListWord);
}
result.add(word);
}
}
memo.put(s, result);
returnresult;
}
publicstaticvoidmain(String[] args) {
BB3wordBreak = newBB3();
String[] words = { "cat", "cats", "and", "sand", "dog", "apple", "pen", "applepen", "pine", "pineapple", "cats",
"dog", "sand", "and", "cat", "wash", "rag" };
Set<String> wordDict = newHashSet<>(Arrays.asList(words));
StringtoBreak1 = "catsanddog";
StringtoBreak2 = "pineapplepenapple";
StringtoBreak3 = "helloworld";
List<String> splitWords1 = wordBreak.breakWords(toBreak1, wordDict);
for (Stringw : splitWords1) {
System.out.print(w + " ");
}
System.out.println();
List<String> splitWords2 = wordBreak.breakWords(toBreak2, wordDict);
for (Stringw : splitWords2) {
System.out.print(w + " ");
}
System.out.println();
List<String> splitWords3 = wordBreak.breakWords(toBreak3, wordDict);
for (Stringw : splitWords3) {
System.out.print(w + " ");
}
return;
}
}