首页 > 其他 > 详细

leetcode 692. Top K Frequent Words

时间:2019-12-28 23:22:45      阅读:80      评论:0      收藏:0      [点我收藏+]
 function Node() {
      this.endCount = 0
      this.word = ''
      this.children = {}
    }
    class Tire {
      constructor() {
        this.root = new Node()
      }
      addWord(word) {
        var node = this.root;
        for (let next of word) {
          if (!node.children[next]) {
            node.children[next] = new Node()
          }
          node = node.children[next]
        }
        node.word = word;
        node.endCount++
      }
      search(k) {
        var ret = []
        innerSearch(this.root, k, ret)
        return ret
      }
    }
    function innerSearch(node, k, ret) {
      if (node) {
        if (node.endCount === k) {
          ret.push(node.word)
        }
        for (let next in node.children) {
          innerSearch(node.children[next], k, ret)
        }
      }
    }

    var topKFrequent = function (words, k) {
      var tire = new Tire;
      for (let word of words) {
        tire.addWord(word)
      }
      return tire.search(k)
    };

leetcode 692. Top K Frequent Words

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

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