zoukankan      html  css  js  c++  java
  • leetcode 745 Prefix and Suffix Search

     
        var WordFilter = function (words) {
          this.trie = {}, idx = 0;
          for (let word of words) {
            let m = word.length;
            let paths = [];
            for (let i = 0; i <= m; i++) {
              this.buildTrie(word.substr(m - i, m) + '_' + word, idx);
            }
            idx++
          }
        };
    
    
        WordFilter.prototype.buildTrie = function (str, weight) {
          console.log(str)
          let trie = this.trie;
          let flag = false;
          for (let path of str) {
            if (!trie[path]) {
              trie[path] = {}
            }
            if (path === '_') flag = true;
            trie = trie[path];
            trie.weight = flag ? weight : trie.weight;
          }
        }
    
        /** 
         * @param {string} prefix 
         * @param {string} suffix
         * @return {number}
         */
        WordFilter.prototype.f = function (prefix, suffix) {
          let paths = suffix + '_' + prefix;
          let trie = this.trie;
          for (let path of paths) {
            if (!trie[path]) return -1;
            trie = trie[path];
          }
          return trie.weight;
        };
    
    
        var trie = new WordFilter(['apple']);
        console.log(trie.f("a", "e"))// returns 0
        console.log(trie.f("b", ""))
        console.log(trie.f("ap", "le"))
    
  • 相关阅读:
    【24点游戏】cocos2dx 源码
    『Python题库
    『Python题库
    【python安装】Windows上安装和创建python开发环境
    『Linux基础
    『Linux基础
    『Linux基础
    『Linux基础
    『Linux基础
    『Python基础-14』匿名函数 `lambda`
  • 原文地址:https://www.cnblogs.com/rubylouvre/p/12116957.html
Copyright © 2011-2022 走看看