Implement a simple spreadsheet where:
Methods:
Spreadsheet(int rows) → initializes spreadsheetvoid setCell(String cell, int value) → sets a cell valuevoid resetCell(String cell) → resets cell to 0int getValue(String formula) → evaluates a formula string1 <= rows <= 10001 <= values <= 10^6Use a HashMap to store cell values with cell references as keys.
Operations:
setCell: Store value in HashMap with cell reference as keyresetCell: Set cell value to 0 in HashMapgetValue: Parse formula string, evaluate each term, sum resultsFormula parsing:
Why this approach works:
Alternative approaches considered:
Example Operations:
Spreadsheet obj = new Spreadsheet(3);
obj.setCell("A1", 5);
obj.setCell("B1", 10);
obj.getValue("=A1+B1+3"); // returns 18
obj.resetCell("A1");
obj.getValue("=A1+B1+3"); // returns 13
Step-by-step execution:
import java.util.*;
class Spreadsheet {
private Map<String, Integer> cellMap = new HashMap<>();
public Spreadsheet(int rows) {
// rows parameter can be used for validation if needed
}
public void setCell(String cell, int value) {
cellMap.put(cell, value);
}
public void resetCell(String cell) {
cellMap.put(cell, 0);
}
public int getValue(String formula) {
int sum = 0;
// skip '=' at start
for (String s : formula.substring(1).split("\\+")) {
sum += mapToValue(s.trim());
}
return sum;
}
private int mapToValue(String s) {
return Character.isLetter(s.charAt(0)) ? cellMap.getOrDefault(s, 0) : Integer.parseInt(s);
}
}