|
20 | 20 |
|
21 | 21 | public class Test2 {
|
22 | 22 |
|
23 |
| - class WordDistance { |
| 23 | + public class AutocompleteSystem { |
24 | 24 |
|
25 |
| - public WordDistance(String[] words) { |
26 |
| - HashMap<String, List<>> |
| 25 | + class TrieNode { |
| 26 | + Map<Character, TrieNode> children; |
| 27 | + Map<String, Integer> counts; |
| 28 | + boolean isWord; |
| 29 | + public TrieNode() { |
| 30 | + children = new HashMap<Character, TrieNode>(); |
| 31 | + counts = new HashMap<String, Integer>(); |
| 32 | + isWord = false; |
| 33 | + } |
27 | 34 | }
|
28 | 35 |
|
29 |
| - public int shortest(String word1, String word2) { |
| 36 | + class Pair { |
| 37 | + String s; |
| 38 | + int c; |
| 39 | + public Pair(String s, int c) { |
| 40 | + this.s = s; this.c = c; |
| 41 | + } |
| 42 | + } |
| 43 | + |
| 44 | + TrieNode root; |
| 45 | + String prefix; |
| 46 | + |
| 47 | + |
| 48 | + public AutocompleteSystem(String[] sentences, int[] times) { |
| 49 | + root = new TrieNode(); |
| 50 | + prefix = ""; |
| 51 | + |
| 52 | + for (int i = 0; i < sentences.length; i++) { |
| 53 | + add(sentences[i], times[i]); |
| 54 | + } |
| 55 | + } |
| 56 | + |
| 57 | + private void add(String s, int count) { |
| 58 | + TrieNode curr = root; |
| 59 | + for (char c : s.toCharArray()) { |
| 60 | + TrieNode next = curr.children.get(c); |
| 61 | + if (next == null) { |
| 62 | + next = new TrieNode(); |
| 63 | + curr.children.put(c, next); |
| 64 | + } |
| 65 | + curr = next; |
| 66 | + curr.counts.put(s, curr.counts.getOrDefault(s, 0) + count); |
| 67 | + } |
| 68 | + curr.isWord = true; |
| 69 | + } |
| 70 | + |
| 71 | + public List<String> input(char c) { |
| 72 | + if (c == '#') { |
| 73 | + add(prefix, 1); |
| 74 | + prefix = ""; |
| 75 | + return new ArrayList<String>(); |
| 76 | + } |
| 77 | + |
| 78 | + prefix = prefix + c; |
| 79 | + TrieNode curr = root; |
| 80 | + for (char cc : prefix.toCharArray()) { |
| 81 | + TrieNode next = curr.children.get(cc); |
| 82 | + if (next == null) { |
| 83 | + return new ArrayList<String>(); |
| 84 | + } |
| 85 | + curr = next; |
| 86 | + } |
| 87 | + |
| 88 | + PriorityQueue<Pair> pq = new PriorityQueue<>((a, b) -> (a.c == b.c ? a.s.compareTo(b.s) : b.c - a.c)); |
| 89 | + for (String s : curr.counts.keySet()) { |
| 90 | + pq.add(new Pair(s, curr.counts.get(s))); |
| 91 | + } |
30 | 92 |
|
| 93 | + List<String> res = new ArrayList<String>(); |
| 94 | + for (int i = 0; i < 3 && !pq.isEmpty(); i++) { |
| 95 | + res.add(pq.poll().s); |
| 96 | + } |
| 97 | + return res; |
31 | 98 | }
|
32 | 99 | }
|
33 | 100 | }
|
0 commit comments