-
Notifications
You must be signed in to change notification settings - Fork 0
/
contact.ts
105 lines (76 loc) · 2.02 KB
/
contact.ts
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
96
97
98
99
100
101
102
103
104
105
'use strict';
import { WriteStream, createWriteStream } from 'fs';
process.stdin.resume();
process.stdin.setEncoding('utf-8');
let inputString: string = '';
let inputLines: string[] = [];
let currentLine: number = 0;
process.stdin.on('data', function (inputStdin: string): void {
inputString += inputStdin;
});
process.stdin.on('end', function (): void {
inputLines = inputString.split('\n');
inputString = '';
main();
});
function readLine(): string {
return inputLines[currentLine++];
}
class ContactNode {
public childs: Map<string, ContactNode>;
public ocurrences: number;
constructor() {
this.childs = new Map();
this.ocurrences = 0;
}
}
class TreeContact {
public root: ContactNode = new ContactNode();
public add(word: string) {
let current = this.root;
for (let count = 0; count < word.length; count++) {
let node = current.childs.get(word[count]);
if (node == null) {
node = new ContactNode();
current.childs.set(word[count], node);
}
node.ocurrences += 1;
current = node;
}
}
public findOcurrences(substr: string) {
let current = this.root;
for (let count = 0; count < substr.length; count++) {
const child = current.childs.get(substr[count]);
if (!child) {
return 0;
}
current = child;
}
return current.ocurrences;
}
}
function contacts(queries: string[][]): number[] {
const trie = new TreeContact();
const ocurrences = [];
for (const q of queries) {
const command = q[0];
const arg = q[1];
if (command == 'add') {
trie.add(arg);
}
if (command == 'find') {
ocurrences.push(trie.findOcurrences(arg));
}
}
return ocurrences;
}
function main() {
const queriesRows: number = parseInt(readLine().trim(), 10);
let queries: string[][] = Array(queriesRows);
for (let i: number = 0; i < queriesRows; i++) {
queries[i] = readLine().replace(/\s+$/g, '').split(' ');
}
const result: number[] = contacts(queries);
console.log(result);
}