Leetcode 2194. Cells in a Range on an Excel Sheet
You are given a string s
that represents the column range in an Excel sheet and two integers row1
and row2
that represent the row range.
The string s
is of the form "A1:C3"
, representing cells from the column represented by A
to C
and from row 1
to 3
.
You need to return a list of all the cells in the range in sorted order.
string s = "K1:L2";
int row1 = 1;
int row2 = 2;
vector<string> = {"K1", "K2", "L1", "L2"};
To solve this problem:
s
to extract the start and end columns.row1
and row2
directly to iterate over the rows.#include <vector>
#include <string>
using namespace std;
vector<string> cellsInRange(string s, int row1, int row2) {
vector<string> result;
// Extract starting and ending column characters
char startCol = s[0];
char endCol = s[3];
// Extract starting and ending rows
int startRow = s[1] - '0';
int endRow = s[4] - '0';
// Iterate over columns from startCol to endCol
for (char col = startCol; col <= endCol; ++col) {
// Iterate over rows from startRow to endRow
for (int row = row1; row <= row2; ++row) {
// Construct the cell string
string cell = string(1, col) + to_string(row);
result.push_back(cell);
}
}
return result;
}
The time complexity is (O(C \times R)), where:
In each iteration, you create one cell string and add it to the vector, leading to a linear complexity relative to the number of cells.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?