[Algorithm] Search for matching words
Implement an autocomplete system. That is, given a query string
sand a set of all possible query strings, return all strings in the set that have s as a prefix.For example, given the query string
deand the set of strings [dog,deer,deal], return [deer,deal].Hint: Try preprocessing the dictionary into a more efficient data structure to speed up queries.
It is using the Trie data stucture, check thist post;
The only changes is that when we search for words, it is partially matched + whole word match.
Which means if we search 'de', it should return [deer, deal],
if we search 'deer', it should return [deer],
if we search 'deerr', it should return [].
function Node () {
  return {
    keys: new Map(),
    isEnd: false
  }
}
function Trie () {
  return {
    root: new Node(),
    // Add words into the tree
    // Recursive
    add(word, node = this.root) {
      // If there is no word, means it reach the end
      if (word.length === ) {
        node.isEnd = true;
        return;
      }
      const [head, ...rest] = word;
      // If char is not set, then create a new Node to hold char
      // Otherwise, continue
      if (!node.keys.has(head)) {
        node.keys.set(head, new Node(head));
      }
      // Continue with three
      this.add(rest, node.keys.get(head));
    },
    // Print all the words in the tree
    print () {
      let words = [];
      // Helper function, Recursive
      function search (node = this.root, string = '') {
        // Make sure we have keys
        if (node.keys.size !== ) {
          for (let key of node.keys.keys()) {
            // update node, update string
            search(node.keys.get(key), string.concat(key));
          }
          // if reach the end, push to the words
          if (node.isEnd) {
            words.push(string);
          }
        } else {
          // If there is no keys, then push the avaialbe string to the words
          string.length >  ? words.push(string) : null;
        }
      }
      search(this.root, '');
      return words.length >  ? words : null;
    },
    // Find the words based on input
    find (input) {
      let words = [];
      function search(node = this.root, string = '', input) {
        if (node.keys.size !== ) {
          for (let key of node.keys.keys()) {
            // if the key is the same as input[0]
            // becasue we want the whole word, so continue with current trees
            if (key === input[] || input.length === ) {
              let rest = input.length ===  ? '': input.substr();
              search(node.keys.get(key), string.concat(key), rest);
            }
          }
        } else {
          // In case of input is 'cattt', then return undefined
          if (input.length !== ) {
            return [];
          }
          string.length >  ? words.push(string) : [];
        }
      }
      search(this.root, '', input);
      return words.length >  ? words : [];
    }
  }
}
function searchWords () {
  const data = ['dog', 'dollar', 'cat', 'drag'];
  const trie = new Trie();
  data.forEach(d => trie.add(d));
  console.log(trie.find('do')); // [ 'dog', 'dollar' ]
  console.log(trie.print()); // [ 'dog', 'dollar', 'drag', 'cat' ]
}
searchWords();
[Algorithm] Search for matching words的更多相关文章
- [Algorithm] Search element in a circular sorted array
		
function findInCircularlySortedAry (ary = [], target) { ) { ; } ) { ] === target ? : -; } let , high ...
 - Deep Dive into Neo4j 3.5 Full Text Search
		
In this blog we will go over the Full Text Search capabilities available in the latest major release ...
 - 广告召回 Query-Ad Matching
		
小结: 1.最为基础的召回链路就是要保证召回层的相关性,但是相关性高的广告并不一定具有很高的商业价值,所以开始尝试将一些商业化业务指标作为召回的依据 百度凤巢新一代广告召回系统--"莫比乌斯 ...
 - (转)Awesome Courses
		
Awesome Courses Introduction There is a lot of hidden treasure lying within university pages scatte ...
 - w3 parse a url
		
最新链接:https://www.w3.org/TR/html53/ 2.6 URLs — HTML5 li, dd li { margin: 1em 0; } dt, dfn { font-wei ...
 - Computer Vision_18_Image Stitching: Image Alignment and Stitching A Tutorial——2006(book)
		
此部分是计算机视觉部分,主要侧重在底层特征提取,视频分析,跟踪,目标检测和识别方面等方面.对于自己不太熟悉的领域比如摄像机标定和立体视觉,仅仅列出上google上引用次数比较多的文献.有一些刚刚出版的 ...
 - bash5.0参考手册
		
Bash Reference Manual a.summary-letter { text-decoration: none } blockquote.indentedblock { margin-r ...
 - 算法编程Algos Programming
		
算法编程Algos Programming 不同算法的集合,用于编程比赛,如ACM ICPC. 算法按主题划分.大多数算法都可以从文件中按原样运行.每种算法都有一个参考问题,并对其时间和空间复杂度作了 ...
 - 从头到尾彻底理解KMP
		
从头到尾彻底理解KMP 作者:July 时间:最初写于2011年12月,2014年7月21日晚10点 全部删除重写成此文,随后的半个多月不断反复改进. 1. 引言 本KMP原文最初写于2年多前的201 ...
 
随机推荐
- curl_get和curl_post,伪造请求头,绕过防盗链下载文件
			
//curl-get function curl_get($url, $timeout = 10) { $ch = curl_init();//初始化 curl_setopt($ch, CURLOPT ...
 - codevs 1079 回家
			
1079 回家 时间限制: 1 s 空间限制: 128000 KB 题目等级 : 白银 Silver 题目描述 Description 现在是晚餐时间,而母牛们在外面分散的牧场中. 农民约翰按响了电铃 ...
 - bzoj 3283 扩展BSGS + 快速阶乘
			
T2 扩展BSGS T3 快速阶乘 给定整数n,质数p和正整数c,求整数s和b,满足n! / pb = s mod pc 考虑每次取出floor(n/p)个p因子,然后将问题转化为子问题. /*** ...
 - java 反射机制之 getDeclaredMethod()获取方法,然后invoke执行实例对应的方法
			
关于反射中getDeclaredMethod().invoke()的学习,来源于项目中的一行代码: SubjectService.class.getDeclaredMethod(autoMatchCo ...
 - 指针式压力表自动读数:Auto Read the Value of Manometer
			
指针式压力表的自动读数,用摄像头对准压力计,然后实时自动地读取压力计的读数.视频效果如下视频所示,红色数字为识别到的指针读数.
 - HDU 4708 Rotation Lock Puzzle (简单题)
			
Rotation Lock Puzzle Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Oth ...
 - VPP电源控制(VPP Power)-- 由DC-DC变换集成电路MC34063组成
			
http://www.willar.com/article/article_view.asp?id=463 由DC-DC变换集成电路MC34063组成,34063 广泛应用于于DC-DC的电源转换电路 ...
 - SSH深度历险(四)    Maven初步学�
			
这几天接触这个词,非常多遍了,仅仅是浅显的体会到它在GXPT中的优点,功能之强大,又通过网络查询了资料进一步的认识学习了,和大家分享. Maven是基于项目对象模型(POM),能够通过一小段描写叙述信 ...
 - hint.css使用说明
			
GitHub:http://liu12fei08fei.github.io/html/1hint.html hint.css使用说明 用途 快速实现tooltips提示样式 相关资源 官方网站GitH ...
 - 转 Objective-C中不同方式实现锁(一)
			
为什么需要使用锁,当然熟悉多线程的你,自然不会对它觉得陌生. 那你在代码中是否很好的使用了锁的机制呢?你又知道几种实现锁的方法呢? 今天一起来探讨一下Objective-C中几种不同方式实现的锁,在这 ...