Skip to content

Commit 860ff8b

Browse files
committed
fd
1 parent 1c001ed commit 860ff8b

File tree

2 files changed

+72
-16
lines changed

2 files changed

+72
-16
lines changed

test/src/main/java/com/inuker/test/Test2.java

Lines changed: 71 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -20,14 +20,81 @@
2020

2121
public class Test2 {
2222

23-
class WordDistance {
23+
public class AutocompleteSystem {
2424

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+
}
2734
}
2835

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+
}
3092

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;
3198
}
3299
}
33100
}

test/src/main/java/com/inuker/test/main.java

Lines changed: 1 addition & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -27,17 +27,6 @@
2727
public class main {
2828

2929
public static void main(String[] args) {
30-
double[] result = new Test2().calcEquation(new String[][] {
31-
{"a", "b"},
32-
{"b", "c"}
33-
}, new double[] {
34-
2.0f, 3.0f
35-
}, new String[][] {
36-
{"a", "c"},
37-
{"b", "c"}
38-
});
39-
for (double f : result) {
40-
System.out.print(f + " ");
41-
}
30+
4231
}
4332
}

0 commit comments

Comments
 (0)