Longest Word in Dictionary LeetCode solution in Java

1
class Solution {
2
private class Node {
3
Node[] sub;
4

5
Node() {
6
sub = new Node[26];
7
}
8
}
9

10
Node root;
11
StringBuilder ans;
12

13
private void buildTire(String word) {
14
Node temp = root;
15
int n = word.length();
16
for (int i = 0; i < n - 1; i++) {
17
int index = word.charAt(i) - 'a';
18
if (temp.sub[index] == null) return;
19
temp = temp.sub[index];
20
}
21
int index = word.charAt(n - 1) - 'a';
22
temp.sub[index] = new Node();
23

24
if (word.length() > ans.length()) ans = new StringBuilder(word);
25
}
26

27
public String longestWord(String[] words) {
28
this.ans = new StringBuilder();
29
this.root = new Node();
30
PriorityQueue<String> pq = new PriorityQueue<>();
31
pq.addAll(Arrays.asList(words));
32
while (!pq.isEmpty()) buildTire(pq.poll());
33
return ans.toString();
34
}
35
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0