zoukankan      html  css  js  c++  java
  • leetcode 1032. Stream of Characters

    用字典树即可解决。首先在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
    
    
    
  • 相关阅读:
    简单批处理语法结构
    简单批处理常用命令
    简单批处理符号简介
    简单批处理内部命令
    jQuery操作DOM
    jQuery中的事件与动画
    jQuery选择器
    初始面向对象
    初识jQuery
    操作DOM
  • 原文地址:https://www.cnblogs.com/rubylouvre/p/12124448.html
Copyright © 2011-2022 走看看