Created
May 16, 2017 18:39
-
-
Save andykais/507d2854ede429d8bb1304d3ecab5b53 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
process.stdin.resume(); | |
process.stdin.setEncoding('ascii'); | |
var input_stdin = ""; | |
var input_stdin_array = ""; | |
var input_currentline = 0; | |
process.stdin.on('data', function (data) { | |
input_stdin += data; | |
}); | |
process.stdin.on('end', function () { | |
input_stdin_array = input_stdin.split("\n"); | |
main(); | |
}); | |
function readLine() { | |
return input_stdin_array[input_currentline++]; | |
} | |
/////////////// ignore above this line //////////////////// | |
let recursiveCheck = (current) => { | |
let numFound = 0 | |
for (let i in current) { | |
let letter = current[i] | |
if (i === '$') numFound++ | |
else numFound += recursiveCheck(letter) | |
} | |
return numFound | |
} | |
class Trie { | |
constructor() { | |
this.head = {} | |
} | |
add(word) { | |
let current = this.head | |
for (let i in word) { | |
let letter = word[i] | |
if (!current[letter]) current[letter] = {} | |
current = current[letter] | |
} | |
current.$ = 1 //word end marker | |
} | |
numStartWith(word) { | |
let current = this.head | |
for (let i in word) { | |
let letter = word[i] | |
if (!(current[letter])) return 0 | |
current = current[letter] | |
} | |
return recursiveCheck(current) | |
} | |
} | |
function main() { | |
var n = parseInt(readLine()); | |
let trie = new Trie() | |
for(var a0 = 0; a0 < n; a0++){ | |
var op_temp = readLine().split(' '); | |
var op = op_temp[0]; | |
var contact = op_temp[1]; | |
if (op === 'add') | |
trie.add(contact) | |
if (op === 'find') { | |
trie.numStartWith(contact) | |
let count = trie.numStartWith(contact) | |
console.log(count) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment