-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsolution.js
54 lines (54 loc) · 1.37 KB
/
solution.js
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
const filePath = require('path').join(__dirname, 'input');
const [t, ...arr] = require('fs')
.readFileSync(filePath)
.toString()
.trim()
.split('\n');
class Trie {
constructor () {
this._node = new Array(10)
this._isEnd = false
}
add (str) {
if (!str || !str.length) return
let nodes = this._node
let curr = null
for (let i = 0; i < str.length; i ++) {
let num = +str[i];
if (!nodes[num]) {
nodes[num] = new Trie()
}
curr = nodes[num];
nodes = nodes[num]._node
}
curr._isEnd = true
}
check (str) {
let nodes = this._node
let curr = null
for (let i = 0; i < str.length; i++) {
let num = +str[i]
curr = nodes[num]
if (!curr) return false
if (curr?._isEnd && i < str.length - 1) {
return false
}
nodes = curr._node
}
return true
}
}
function solution (t, arr) {
let test = 0;
let i = 0;
while (test++ < t) {
const n = +arr[i++];
const list = arr.slice(i, i + n);
const trie = new Trie();
list.forEach(v => trie.add(v));
const check = list.some(v => !trie.check(v))
console.log(check ? 'NO' : 'YES');
i += n;
}
}
solution(+t, arr);