Ruby's Louvre

每天学习一点点算法

导航

leetcode 1023. Camelcase Matching

使用前缀树, 多个字符串匹配一个模式

  function Node() {
      this.children = {}
    }
    class Trie {
      constructor() {
        this.root = new Node()
      }
      insert(word) {
        var node = this.root;
        for (let c of word) {
          if (!node.children[c]) {
            node.children[c] = new Node
          }

          node = node.children[c]
        }
        node.word = word;
      }
      search(word) {
        var hash = {}
        innerSearch(this.root, word, 0, true, hash)
        return hash;
      }

    }
    function innerSearch(node, word, index, value, hash) {
      if (node.word) {
        if (index >= word.length) {
          hash[node.word] = value;
        } else {
          hash[node.word] = false
        }
      }

      var a = word[index]
      for (let c in node.children) {
        if (c === a) { //都是大写或小写,并且字母一样
          innerSearch(node.children[c], word, index + 1, value, hash)
        } else {
          var code = c.charCodeAt(0)
          if (code >= 65 && code <= 90) {
            innerSearch(node.children[c], word, index, false, hash)
          } else {
            innerSearch(node.children[c], word, index, value, hash)
          }

        }
      }
      return true
    }

    function camelMatch(queries, pattern) {
      let trie = new Trie
      for (let word of queries) {
        trie.insert(word)
      }
      let hash = trie.search(pattern)
      let ret = []
      for (let word of queries) {
        ret.push(hash[word])
      }

      console.log(ret)
      return ret;
    }
    camelMatch(["FooBar", "FooBarTest", "FootBall", "FrameBuffer", "ForceFeedBack"], 'FB')
    camelMatch(["FooBar", "FooBarTest", "FootBall", "FrameBuffer", "ForceFeedBack"], 'FoBa')
    camelMatch(["FooBar", "FooBarTest", "FootBall", "FrameBuffer", "ForceFeedBack"], 'FBT')
机器瞎学/数据掩埋/模式混淆/人工智障/深度遗忘/神经掉线/计算机幻觉/专注单身二十五年

posted on 2019-12-31 02:32  司徒正美  阅读(219)  评论(0编辑  收藏  举报