码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode 692. Top K Frequent Words

时间:2019-12-28 22:44:48      阅读:65      评论:0      收藏:0      [点我收藏+]

标签:++   tco   root   leetcode   new t   add   pre   let   end   

 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

标签:++   tco   root   leetcode   new t   add   pre   let   end   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!