2025-09-19 Daily Challenge
Today I have done leetcode's September LeetCoding Challenge with cpp.
September LeetCoding Challenge 19
Description
Design Spreadsheet
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", whereXandYare 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.
Example 1:
Input:
["Spreadsheet", "getValue", "setCell", "getValue", "setCell", "getValue", "resetCell", "getValue"]
[[3], ["=5+7"], ["A1", 10], ["=A1+6"], ["B2", 15], ["=A1+B2"], ["A1"], ["=A1+B2"]]
Output:
[null, 12, null, 16, null, 25, null, 15]
Explanation
Spreadsheet spreadsheet = new Spreadsheet(3); // Initializes a spreadsheet with 3 rows and 26 columnsspreadsheet.getValue("=5+7"); // returns 12 (5+7)
spreadsheet.setCell("A1", 10); // sets A1 to 10
spreadsheet.getValue("=A1+6"); // returns 16 (10+6)
spreadsheet.setCell("B2", 15); // sets B2 to 15
spreadsheet.getValue("=A1+B2"); // returns 25 (10+15)
spreadsheet.resetCell("A1"); // resets A1 to 0
spreadsheet.getValue("=A1+B2"); // returns 15 (0+15)
Constraints:
1 <= rows <= 1030 <= value <= 105- The formula is always in the format
"=X+Y", whereXandYare 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 between1androws. - At most
104calls will be made in total tosetCell,resetCell, andgetValue.
Solution
vector<string> split(string &&s, char spliter = ' ') {
vector<string> result;
for(int i = 0; i < s.length(); ++i) {
string st;
while(i < s.length() && s[i] != spliter) {
st += s[i];
i += 1;
}
if(st.size()) result.emplace_back(st);
}
return result;
}
class Spreadsheet {
map<string, int> data;
int getVal(string expr) {
if(isdigit(expr[0])) return stoi(expr);
return data[expr];
}
public:
Spreadsheet(int rows) {
}
void setCell(string cell, int value) {
data[cell] = value;
}
void resetCell(string cell) {
data[cell] = 0;
}
int getValue(string formula) {
auto xy = split(formula.substr(1), '+');
int x = getVal(xy[0]);
int y = getVal(xy[1]);
return x + y;
}
};
// Accepted
// 658/658 cases passed (131 ms)
// Your runtime beats 31.91 % of cpp submissions
// Your memory usage beats 78.99 % of cpp submissions (137.4 MB)