Guest User

Untitled

a guest
Apr 19th, 2018
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.07 KB | None | 0 0
  1. "use strict";
  2.  
  3. const util = require('util')
  4.  
  5. class TrieNode {
  6. constructor(l) {
  7. this.letter = l;
  8. this.isFullWord = false;
  9. this.letters = {};
  10. this.wordCount = 0;
  11. }
  12.  
  13. isAdjacent(letter) {
  14. return letter in this.letters
  15. }
  16.  
  17. add (name, i) {
  18.  
  19. this.wordCount++;
  20.  
  21. if ( name.length == i ) {
  22. this.isFullWord = true;
  23. return
  24. }
  25.  
  26. let letter = name[i];
  27. if (!this.isAdjacent(letter)) {
  28. this.letters[ letter ] = new TrieNode(letter);
  29. }
  30.  
  31. this.letters[ letter ].add( name, i+1 );
  32. }
  33.  
  34. countByPrefix (prefix, i) {
  35. let wordCount = 0;
  36. if (prefix.length == i) {
  37. wordCount = this.wordCount;
  38. } else {
  39. let letter = prefix[i];
  40. if (letter in this.letters) {
  41. wordCount = this.letters[ letter ].countByPrefix(prefix, i+1)
  42. }
  43. }
  44. return wordCount;
  45. }
  46. }
  47.  
  48. class Agenda {
  49.  
  50. constructor() {
  51. this.agenda = {};
  52. }
  53.  
  54. addContact(name) {
  55. let letter = name[0];
  56.  
  57. if (! (letter in this.agenda)) {
  58. this.agenda[ letter ] = new TrieNode(letter);
  59. }
  60.  
  61. this.agenda[ letter ].add(name, 1);
  62. }
  63.  
  64. countByPrefix(prefix) {
  65. let letter = prefix[0];
  66.  
  67. if ( letter in this.agenda ) {
  68. return this.agenda[ letter ].countByPrefix(prefix, 1);
  69. }
  70.  
  71. return 0
  72. }
  73. }
  74.  
  75.  
  76. let agenda = new Agenda();
  77.  
  78. agenda.addContact("s");
  79. agenda.addContact("ss");
  80. agenda.addContact("sss");
  81. agenda.addContact("ssss");
  82. agenda.addContact("sssss");
  83. console.log(agenda.countByPrefix("s"))
  84. console.log(agenda.countByPrefix("ss"))
  85. console.log(agenda.countByPrefix("sss"))
  86. console.log(agenda.countByPrefix("ssss"))
  87. console.log(agenda.countByPrefix("sssss"))
  88. console.log(agenda.countByPrefix("ssssss"))
  89.  
  90.  
  91. console.log("=====")
  92.  
  93. agenda.addContact("hack");
  94. agenda.addContact("hackerrank");
  95.  
  96.  
  97. console.log(agenda.countByPrefix("hac"))
  98. console.log(agenda.countByPrefix("hak"))
  99. console.log(agenda.countByPrefix("hackerrank"))
Add Comment
Please, Sign In to add comment