-
Notifications
You must be signed in to change notification settings - Fork 0
/
PhoneList.java
69 lines (56 loc) · 1.42 KB
/
PhoneList.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
/* https://www.spoj.com/problems/PHONELST/
#trie
*/
import java.util.Scanner;
class PhoneList {
static final int MAX = 10;
static class TrieNode {
TrieNode[] childNode;
boolean isEndNumber;
TrieNode() {
childNode = new TrieNode[MAX];
isEndNumber = false;
}
}
public static boolean addNumber(TrieNode root, String number) {
TrieNode pTmp = root;
boolean ans = true;
boolean addNewNodeFlg = false;
int level, idx;
int length = number.length();
for (level = 0; level < length; level++) {
idx = number.charAt(level) - '0';
if (pTmp.childNode[idx] == null) {
addNewNodeFlg = true;
pTmp.childNode[idx] = new TrieNode();
}
pTmp = pTmp.childNode[idx];
if (pTmp.isEndNumber && level < length - 1) {
ans = false;
}
}
pTmp.isEndNumber = true;
if (!addNewNodeFlg) {
ans = false;
}
return ans;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int testcases, numbers;
String number;
testcases = sc.nextInt();
for (int t = 0; t < testcases; t++) {
TrieNode root = new TrieNode();
boolean ans = true;
numbers = sc.nextInt();
for (int i = 0; i < numbers; i++) {
number = sc.next();
if (!addNumber(root, number)) {
ans = false;
}
}
System.out.println((ans ? "YES" : "NO"));
}
}
}