You are given a string s
that represents a range of cells in an Excel sheet, such as “K1:L2”. The range indicates that your task is to cover cells from the top-left cell to the bottom-right cell.
Return the list of cell names in order from the top-left to the bottom-right.
Example:
s = "K1:L2"
["K1", "K2", "L1", "L2"]
Constraints:
s
will always be a valid range, formatted as two cell names separated by a colon (“:”).s
always be a valid Excel range format?Assuming constraints generally imply:
s = "K1:L2"
, we separate it into start = "K1"
and end = "L2"
.def cellsInRange(s: str) -> List[str]:
# Split the input
start, end = s.split(':')
# Extract column letters and row numbers
start_col, start_row = start[0], int(start[1:])
end_col, end_row = end[0], int(end[1:])
# Generate the list of cells
result = []
for col in range(ord(start_col), ord(end_col) + 1):
for row in range(start_row, end_row + 1):
cell = f"{chr(col)}{row}"
result.append(cell)
return result
start_col
and end_col
are the starting and ending columns in character form, converted to ASCII using ord
.start_row
and end_row
are the starting and ending rows in integer form.start_col
to end_col
.start_row
to end_row
.chr
for columns and string concatenation for rows.This approach ensures all cells within the specified range are covered correctly and efficiently.
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?