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