|
1 | 1 | class Solution {
|
2 |
| - public String longestWord(String[] words) { |
3 |
| - Arrays.sort(words); |
4 |
| - |
5 |
| - Set<String> built = new HashSet<String>(); |
6 |
| - String ans = ""; |
7 |
| - |
8 |
| - for (String word : words) { |
9 |
| - if (word.length() == 1 || built.contains(word.substring(0, word.length() - 1))) { |
10 |
| - ans = word.length() > ans.length() ? word : ans; |
11 |
| - built.add(word); |
12 |
| - } |
13 |
| - } |
14 |
| - return ans; |
| 2 | + Map<Integer, List<String>> map; |
| 3 | + int maxVal; |
| 4 | + public String longestWord(String[] words) { |
| 5 | + map = new HashMap<>(); |
| 6 | + maxVal = Integer.MIN_VALUE; |
| 7 | + Node root = new Node('-'); |
| 8 | + Arrays.sort(words); |
| 9 | + for (String word : words) { |
| 10 | + addWord(word, root, 0); |
15 | 11 | }
|
| 12 | + if (maxVal == Integer.MIN_VALUE) { |
| 13 | + return ""; |
| 14 | + } |
| 15 | + List<String> possibleAns = map.get(maxVal); |
| 16 | + Collections.sort(possibleAns); |
| 17 | + return possibleAns.get(0); |
| 18 | + } |
| 19 | + |
| 20 | + private void addWord(String word, Node root, int idx) { |
| 21 | + char c = word.charAt(idx); |
| 22 | + if (!root.children.containsKey(c) && idx != word.length() - 1) { |
| 23 | + return; |
| 24 | + } |
| 25 | + if (!root.children.containsKey(c)) { |
| 26 | + root.children.put(c, new Node(c)); |
| 27 | + } |
| 28 | + root = root.children.get(c); |
| 29 | + if (idx == word.length() - 1) { |
| 30 | + root.isWord = true; |
| 31 | + int wordLength = word.length(); |
| 32 | + map.computeIfAbsent(wordLength, k -> new ArrayList<>()).add(word); |
| 33 | + maxVal = Math.max(maxVal, wordLength); |
| 34 | + } |
| 35 | + else { |
| 36 | + addWord(word, root, idx + 1); |
| 37 | + } |
| 38 | + } |
| 39 | +} |
| 40 | + |
| 41 | +class Node { |
| 42 | + char val; |
| 43 | + boolean isWord; |
| 44 | + Map<Character, Node> children; |
| 45 | + |
| 46 | + public Node(char val) { |
| 47 | + this.val = val; |
| 48 | + isWord = true; |
| 49 | + children = new HashMap<>(); |
| 50 | + } |
16 | 51 | }
|
0 commit comments