ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

leetcode 1032. Stream of Characters

2019-12-31 15:00:57  阅读:283  来源: 互联网

标签:return word var streamChecker Characters 1032 query false leetcode


用字典树即可解决。首先在init的时候,把words中所有word逆置后存入字典树中;在query的时候,也有逆序的方式记录所有历史query过的值,同时判断其前缀是否存在于字典树中即可。


    function Node() {
      this.children = {}
    }
    class StreamChecker {
      constructor(words) {
        this.history = ''
        this.root = new Node;
        for (let word of words) {
          this.insert(word.split('').reverse().join(''))
        }
      }
      insert(word) {
        var node = this.root;
        for (let c of word) {
          var next = node.children[c]
          if (!next) {
            node.children[c] = next = new Node
          }
          node = next;
        }
        node.word = word;
      }
      search(word) {

        var current = this.root;
        for (var i = this.history.length - 1; i >= 0; i--) {
          var ch = this.history[i]
          if (current.children[ch] == null) {
            return false;
          }
          current = current.children[ch];
          if (current.word) {
            return true;
          }
        }
        return false

      }
      query(q) {
        this.history += q
        var val = this.search()
        console.log(val)
        return val
      }

    }

    var streamChecker = new StreamChecker(["cd", "f", "kl"]); // init the dictionary.
    streamChecker.query('a');          // return false
    streamChecker.query('b');          // return false
    streamChecker.query('c');          // return false
    streamChecker.query('d');          // return true, because 'cd' is in the wordlist
    streamChecker.query('e');          // return false
    streamChecker.query('f');          // return true, because 'f' is in the wordlist
    streamChecker.query('g');          // return false
    streamChecker.query('h');          // return false
    streamChecker.query('i');          // return false
    streamChecker.query('j');          // return false
    streamChecker.query('k');          // return false
    streamChecker.query('l');          // return true, because 'kl' is in the wordlist

标签:return,word,var,streamChecker,Characters,1032,query,false,leetcode
来源: https://www.cnblogs.com/rubylouvre/p/12124448.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有