LeetCode-in-Java

2194. Cells in a Range on an Excel Sheet

Easy

A cell (r, c) of an excel sheet is represented as a string "<col><row>" where:

You are given a string s in the format "<col1><row1>:<col2><row2>", where <col1> represents the column c1, <row1> represents the row r1, <col2> represents the column c2, and <row2> represents the row r2, such that r1 <= r2 and c1 <= c2.

Return the list of cells (x, y) such that r1 <= x <= r2 and c1 <= y <= c2. The cells should be represented as strings in the format mentioned above and be sorted in non-decreasing order first by columns and then by rows.

Example 1:

Input: s = “K1:L2”

Output: [“K1”,”K2”,”L1”,”L2”]

Explanation:

The above diagram shows the cells which should be present in the list.

The red arrows denote the order in which the cells should be presented.

Example 2:

Input: s = “A1:F1”

Output: [“A1”,”B1”,”C1”,”D1”,”E1”,”F1”]

Explanation:

The above diagram shows the cells which should be present in the list.

The red arrow denotes the order in which the cells should be presented.

Constraints:

Solution

import java.util.ArrayList;
import java.util.List;

public class Solution {
    public List<String> cellsInRange(String str) {
        char[] c = str.toCharArray();
        List<String> strings = new ArrayList<>();
        for (char i = c[0]; i <= c[3]; i++) {
            for (char j = c[1]; j <= c[4]; j++) {
                strings.add(new String(new char[] {i, j}));
            }
        }
        return strings;
    }
}