Problem
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 specifiedcell
. 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"
, whereX
andY
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.
Examples
Example 1
|
|
Constraints
1 <= rows <= 10^3
0 <= value <= 10^5
- The formula is always in the format
"=X+Y"
, whereX
andY
are either valid cell references or non-negative integers with values less than or equal to105
. - Each cell reference consists of a capital letter from
'A'
to'Z'
followed by a row number between1
androws
. - At most
104
calls will be made in total tosetCell
,resetCell
, andgetValue
.
Solution
Method 1 – 2D Array and Simple Parsing
Intuition
We can use a 2D array to represent the spreadsheet, mapping columns ‘A’-‘Z’ to indices 0-25 and rows to indices 0-based. For formulas, we parse the operands and check if they are cell references or integers, then sum their values.
Approach
- Use a 2D array
mat
of sizerows x 26
to store cell values, initialized to 0. - For
setCell(cell, value)
, parse the column and row, and set the value inmat
. - For
resetCell(cell)
, set the corresponding cell to 0. - For
getValue(formula)
, parse the formula (always in the form=X+Y
). For each operand, if it is a cell reference, get its value frommat
; if it is an integer, parse it directly. Return the sum.
Code
|
|
|
|
|
|
Complexity
- ⏰ Time complexity:
O(1)
per operation, as all operations are direct array accesses and simple parsing. - 🧺 Space complexity:
O(rows*26)
, for the spreadsheet matrix.