|
| 1 | +/** |
| 2 | + * 3484. Design Spreadsheet |
| 3 | + * https://leetcode.com/problems/design-spreadsheet/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * A spreadsheet is a grid with 26 columns (labeled from 'A' to 'Z') and a given number |
| 7 | + * of rows. Each cell in the spreadsheet can hold an integer value between 0 and 105. |
| 8 | + * |
| 9 | + * Implement the Spreadsheet class: |
| 10 | + * - Spreadsheet(int rows) Initializes a spreadsheet with 26 columns (labeled 'A' to 'Z') |
| 11 | + * and the specified number of rows. All cells are initially set to 0. |
| 12 | + * - void setCell(String cell, int value) Sets the value of the specified cell. The cell |
| 13 | + * reference is provided in the format "AX" (e.g., "A1", "B10"), where the letter represents |
| 14 | + * the column (from 'A' to 'Z') and the number represents a 1-indexed row. |
| 15 | + * - void resetCell(String cell) Resets the specified cell to 0. |
| 16 | + * - int getValue(String formula) Evaluates a formula of the form "=X+Y", where X and Y are |
| 17 | + * either cell references or non-negative integers, and returns the computed sum. |
| 18 | + * |
| 19 | + * Note: If getValue references a cell that has not been explicitly set using setCell, its |
| 20 | + * value is considered 0. |
| 21 | + */ |
| 22 | + |
| 23 | +/** |
| 24 | + * @param {number} rows |
| 25 | + */ |
| 26 | +var Spreadsheet = function(rows) { |
| 27 | + this.cellValues = new Map(); |
| 28 | + this.totalRows = rows; |
| 29 | +}; |
| 30 | + |
| 31 | +/** |
| 32 | + * @param {string} cell |
| 33 | + * @param {number} value |
| 34 | + * @return {void} |
| 35 | + */ |
| 36 | +Spreadsheet.prototype.setCell = function(cell, value) { |
| 37 | + this.cellValues.set(cell, value); |
| 38 | +}; |
| 39 | + |
| 40 | +/** |
| 41 | + * @param {string} cell |
| 42 | + * @return {void} |
| 43 | + */ |
| 44 | +Spreadsheet.prototype.resetCell = function(cell) { |
| 45 | + this.cellValues.delete(cell); |
| 46 | +}; |
| 47 | + |
| 48 | +/** |
| 49 | + * @param {string} formula |
| 50 | + * @return {number} |
| 51 | + */ |
| 52 | +Spreadsheet.prototype.getValue = function(formula) { |
| 53 | + const expression = formula.slice(1); |
| 54 | + const operands = expression.split('+'); |
| 55 | + |
| 56 | + const leftValue = this.parseOperand(operands[0]); |
| 57 | + const rightValue = this.parseOperand(operands[1]); |
| 58 | + |
| 59 | + return leftValue + rightValue; |
| 60 | +}; |
| 61 | + |
| 62 | +/** |
| 63 | + * @param {string} operand |
| 64 | + * @return {number} |
| 65 | + */ |
| 66 | +Spreadsheet.prototype.parseOperand = function(operand) { |
| 67 | + if (/^\d+$/.test(operand)) { |
| 68 | + return parseInt(operand); |
| 69 | + } |
| 70 | + return this.cellValues.get(operand) || 0; |
| 71 | +}; |
0 commit comments