Last active
February 6, 2017 20:45
-
-
Save jasonwaters/f7b8eb87f6148f05c4e9649cb4968754 to your computer and use it in GitHub Desktop.
Tries: Contacts
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
| // https://www.hackerrank.com/challenges/ctci-contacts | |
| function Trie() { | |
| this.data = {}; | |
| } | |
| Trie.prototype.process = function(op, str) { | |
| if(op === 'add') { | |
| let data = this.data; | |
| for(let char of str) { | |
| if(!data[char]) { | |
| data[char] = {count: 0} | |
| } | |
| data[char].count++; | |
| data = data[char]; | |
| } | |
| }else if(op === 'find') { | |
| let data = this.data; | |
| for(let char of str) { | |
| if(typeof data[char] != 'undefined') { | |
| data = data[char]; | |
| }else { | |
| console.log(0); | |
| return; | |
| } | |
| } | |
| console.log(data.count); | |
| } | |
| } | |
| Trie.prototype.dump = function() { | |
| console.log(this.data); | |
| } | |
| //////////////////// | |
| let input = `4 | |
| add hack | |
| add hackerrank | |
| find hac | |
| find hak`; | |
| let commands = input.split('\n').slice(1).map(line => line.split(' ')); | |
| let t = new Trie(); | |
| commands.forEach(command => t.process(command[0], command[1])); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment