3484. Design Spreadsheet

Leetcode link

题目简介

题目要求我们实现一个由 26 列(字母A-Z)rows 行所组成的表格并实现如下功能:

  • void setCell(String cell, int value):设置特定的格子为 value
  • void resetCell(String cell):重置特定格子为 0
  • int getValue(String formula):使用 =X+Y 公式计算两个格子的和,其中 X 与 Y 可以是格子,也可以是数字

格子的表达方式为字母+数字,比如:A1, B10

解题思路

这题一开始会让人想到用一个二维数组来将表格构建出来,但是其实不用这么麻烦

我们只需要一个 Map 来保存格子与值的对应关系就好,对于没有在 map 中的格子,我们默认置零

需要特别注意的是,公式的字一个字符是 =,且公式有可能包含纯数字,所以需要判断一下

Javascript

/**
 * @param {number} rows
 */
var Spreadsheet = function(rows) {
    this.map = new Map()
};

/** 
 * @param {string} cell 
 * @param {number} value
 * @return {void}
 */
Spreadsheet.prototype.setCell = function(cell, value) {
    this.map.set(cell, value)
};

/** 
 * @param {string} cell
 * @return {void}
 */
Spreadsheet.prototype.resetCell = function(cell) {
    this.map.delete(cell)
};

/** 
 * @param {string} formula
 * @return {number}
 */
Spreadsheet.prototype.getValue = function(formula) {
    const [c1, c2] = formula.substring(1).split('+')
    let v1 = 0
    if(!(/^[A-Za-z]$/.test(c1[0]))) {
        v1 = parseInt(c1)
    }else if(this.map.has(c1)) {
        v1 = this.map.get(c1)
    }

    let v2 = 0
    if(!(/^[A-Za-z]$/.test(c2[0]))) {
        v2 = parseInt(c2)
    }else if(this.map.has(c2)) {
        v2 = this.map.get(c2)
    }

    return v1 + v2
};

results matching ""

    No results matching ""