首页 > 其他 > 详细

leetcode 745 Prefix and Suffix Search

时间:2019-12-29 22:51:16      阅读:90      评论:0      收藏:0      [点我收藏+]
 
    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"))

leetcode 745 Prefix and Suffix Search

原文:https://www.cnblogs.com/rubylouvre/p/12116957.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!