-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLongestPhonePrefixes.java
95 lines (59 loc) · 2.37 KB
/
LongestPhonePrefixes.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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
import java.io.*;
import java.util.*;
public class Solution {
// 2019 Twilio OA assessment problem
public static void main(String[] args) throws Exception {
String[] prefixes = {"213", "21358", "1234", "12"};
String[] phoneNumbers = {"21349049", "1204539492", "123490485904"};
String[] desiredOutput = {"213", "12", "1234"};
String[] output = findPrefixes(prefixes, phoneNumbers);
if (!Arrays.equals(output, desiredOutput)) throw new Exception("Wrong result!");
System.out.println("OK");
}
//Time: O(n*avg) where n is phoneNumbers.length & avg is phoneNumbers average size
//Space: O(m) where m is prefixes.length
public static String[] findPrefixes(String[] prefixes, String[] phoneNumbers) {
String[] sol = new String[phoneNumbers.length];
Trie trie = new Solution.Trie();
for(String prefix: prefixes) trie.insert(prefix);
for(int i = 0; i < phoneNumbers.length; i++) {
String number = phoneNumbers[i];
sol[i] = trie.findLongestPrefix(number);
}
return sol;
}
private static class Trie {
private static class Node {
private static final int DIC_SIZE = 10;
public char value;
public Node[] children = new Node[DIC_SIZE];
public boolean isWord = false;
public Node(char value) {
this.value = value;
}
}
private final Trie.Node root;
public Trie() {
this.root = new Node('*');
}
public void insert(String word) {
Trie.Node current = root;
for(Character letter: word.toCharArray()) {
if(current.children[letter - '0'] == null) current.children[letter - '0'] = new Node(letter);
current = current.children[letter - '0'];
}
current.isWord = true;
}
public String findLongestPrefix(String word) {
Trie.Node current = root;
StringBuilder builder = new StringBuilder();
for(Character letter: word.toCharArray()) {
Trie.Node next = current.children[letter - '0'];
if (next == null) break;
builder.append(letter);
current = next;
}
return builder.toString();
}
}
}