LeetCode-in-Java

3484. Design Spreadsheet

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:

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 columns
spreadsheet.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:

Solution

import java.util.HashMap;
import java.util.Map;

@SuppressWarnings("unused")
public class Spreadsheet {
    private final Map<String, Integer> data = new HashMap<>();

    public Spreadsheet(int rows) {}

    public void setCell(String cell, int value) {
        data.put(cell, value);
    }

    public void resetCell(String cell) {
        data.put(cell, 0);
    }

    public int getValue(String formula) {
        int index = formula.indexOf('+');
        String left = formula.substring(1, index);
        String right = formula.substring(index + 1);
        int x =
                Character.isLetter(left.charAt(0))
                        ? data.getOrDefault(left, 0)
                        : Integer.parseInt(left);
        int y =
                Character.isLetter(right.charAt(0))
                        ? data.getOrDefault(right, 0)
                        : Integer.parseInt(right);
        return x + y;
    }
}

/*
 * Your Spreadsheet object will be instantiated and called as such:
 * Spreadsheet obj = new Spreadsheet(rows);
 * obj.setCell(cell,value);
 * obj.resetCell(cell);
 * int param_3 = obj.getValue(formula);
 */