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
    
    
    
  • 相关阅读:
    es6语法快速上手(转载)
    width百分比
    利用switch case 来运行咱们结婚吧
    利用if else来运行咱们结婚吧
    利用if else 来计算车费
    利用switch case判断是今天的第多少天
    利用if else判断是否及格
    利用if,else判断输入的是不是一个正整数
    再练一遍猜拳
    用if else 判断是不是7的倍数等
  • 原文地址:https://www.cnblogs.com/rubylouvre/p/12124448.html
Copyright © 2011-2022 走看看