Guest User

Untitled

a guest
Feb 19th, 2018
59
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.20 KB | None | 0 0
  1. function Trie() {
  2. this.children = {};
  3. this.isLeaf = null;
  4.  
  5. this.insert = function(str, index) {
  6. if (!str.length) {
  7. this.isLeaf = index;
  8. return;
  9. }
  10. if (this.children[str[0]]) {
  11. this.children[str[0]].insert(str.slice(1), index);
  12. } else {
  13. const trie = new Trie();
  14. trie.insert(str.slice(1), index);
  15. this.children[str[0]] = trie;
  16. }
  17. };
  18.  
  19. this.getIndex = function(str) {
  20. if (this.isLeaf != null) {
  21. return this.isLeaf;
  22. }
  23. if (!str.length || !this.children[str[0]]) {
  24. return null;
  25. }
  26.  
  27. return this.children[str[0]].getIndex(str.slice(1));
  28. };
  29. };
  30.  
  31. /**
  32. * @param {string[]} dict
  33. * @param {string} sentence
  34. * @return {string}
  35. */
  36. var replaceWords = function(dict, sentence) {
  37. const trie = new Trie();
  38. for (let i=0; i<dict.length; ++i) {
  39. trie.insert(dict[i], i);
  40. }
  41. const words = sentence.split(' ');
  42. for (let i=0; i<words.length; ++i) {
  43. const dictIndex = trie.getIndex(words[i]);
  44. if (dictIndex != null) {
  45. words[i] = dict[dictIndex];
  46. }
  47. }
  48. return words.join(' ');
  49. };
Add Comment
Please, Sign In to add comment