-
Notifications
You must be signed in to change notification settings - Fork 46
/
_472.java
68 lines (60 loc) · 1.62 KB
/
_472.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
63
64
65
66
67
68
import java.util.*;
/**
* LeetCode 472 - Concatenated Words
* <p>
* DP + Trie
*/
public class _472 {
static class Trie {
Trie[] ch = new Trie[26];
String s = null;
}
Trie root = null;
Set<String> set;
Map<String, Boolean> map;
private void insert(String s) {
Trie r = root;
for (int i = 0; i < s.length(); i++) {
int ch = s.charAt(i) - 'a';
if (r.ch[ch] == null) r.ch[ch] = new Trie();
r = r.ch[ch];
}
r.s = s;
}
private boolean f(String s) {
if (map.containsKey(s)) return map.get(s);
boolean isok = false;
Trie r = root;
for (int i = 0; i < s.length() - 1; i++) {
int ch = s.charAt(i) - 'a';
if (r.ch[ch] != null) {
r = r.ch[ch];
if (r.s != null) {
String suffix = s.substring(i + 1);
if (set.contains(suffix) || f(suffix)) {
isok = true;
break;
}
}
} else {
break;
}
}
map.put(s, isok);
return isok;
}
public List<String> findAllConcatenatedWordsInADict(String[] words) {
set = new HashSet<>();
map = new HashMap<>();
root = new Trie();
for (String word : words)
if (!word.equals("")) {
set.add(word);
insert(word);
}
List<String> ans = new ArrayList<>();
for (String s : set)
if (f(s)) ans.add(s);
return ans;
}
}