likes
comments
collection
share

30天刷题挑战(二十五)

作者站长头像
站长
· 阅读数 30

题目来源: LeetCode 75 30 天 JavaScript 挑战

208. 实现 Trie (前缀树)

代码

var Trie = function() {
  this.node = new Map()
};

/** 
 * @param {string} word
 * @return {void}
 */
Trie.prototype.insert = function(word) {
    let node = this.node

    for (let ch of word) {
       if (!node.has(ch)) {
         node.set(ch, new Map())
       }
       node = node.get(ch)
    }
    node.set("isEnd", true)
};


Trie.prototype.searchPrefix = function(prefix) {
  let node = this.node

   for (let ch of prefix) {
       if (!node.has(ch)) {
         return false
       }
       node = node.get(ch)
    }

  return node
};


/** 
 * @param {string} word
 * @return {boolean}
 */
Trie.prototype.search = function(word) {
  let node = this.searchPrefix(word)
  return !!node && !!node.get("isEnd")
};

/** 
 * @param {string} prefix
 * @return {boolean}
 */
Trie.prototype.startsWith = function(prefix) {
    return this.searchPrefix(prefix)
};

/**
 * Your Trie object will be instantiated and called as such:
 * var obj = new Trie()
 * obj.insert(word)
 * var param_2 = obj.search(word)
 * var param_3 = obj.startsWith(prefix)
 */

1268. 搜索推荐系统

思路

模拟法,按题意匹配字符

代码

/**
 * @param {string[]} products
 * @param {string} searchWord
 * @return {string[][]}
 */
var suggestedProducts = function(products, searchWord) {
  let res = []

  products.sort()

  for (let i = 0; i < searchWord.length; i++) {
    let temp = []

    products.forEach(p => {
      if (p[i] === searchWord[i]) {
        temp.push(p)
      }
    })

    products = temp
    res.push(products.length > 3 ? products.slice(0, 3) :products) 
  }

 return res
};

2726. 使用方法链的计算器

代码

class Calculator {
  
    /** 
     * @param {number} value
     */
	constructor(value) {
		this.result = value
	}

    /** 
     * @param {number} value
     * @return {Calculator}
     */
	add(value){
		this.result += value
    return this
	}

    /** 
     * @param {number} value
     * @return {Calculator}
     */
	subtract(value){
		this.result -= value
    return this
	}

    /** 
     * @param {number} value
     * @return {Calculator}
     */  
	multiply(value) {
		this.result *= value
    return this
	}

    /** 
     * @param {number} value
     * @return {Calculator}
     */
	divide(value) {
    if (!value) {
      throw Error("Division by zero is not allowed")
    }
		this.result /= value
    return this
	}
  
    /** 
     * @param {number} value
     * @return {Calculator}
     */
	power(value) {
		this.result **= value
    return this
	}
    
    /** 
     * @return {number}
     */
	getResult() {
		return this.result
	}
}

本文完,感谢阅读

转载自:https://juejin.cn/post/7293114988779798569
评论
请登录