LeetCode 题解工作台

Excel 表中某个范围内的单元格

Excel 表中的一个单元格 (r, c) 会以字符串 " " 的形式进行表示,其中: 即单元格的列号 c 。用英文字母表中的 字母 标识。 例如,第 1 列用 'A' 表示,第 2 列用 'B' 表示,第 3 列用 'C' 表示,以此类推。 即单元格的行号 r 。第 r 行就用 整数 r 标识。 …

category

1

题型

code_blocks

5

代码语言

hub

3

相关题

当前训练重点

简单 · String-driven solution strategy

bolt

答案摘要

我们直接遍历范围内的所有单元格,将其添加到答案数组中。 时间复杂度 $O(m \times n)$,空间复杂度 $O(m \times n)$,其中 和 分别为行数和列数的取值范围。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 String-driven solution strategy 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

Excel 表中的一个单元格 (r, c) 会以字符串 "<col><row>" 的形式进行表示,其中:

  • <col> 即单元格的列号 c 。用英文字母表中的 字母 标识。
    • 例如,第 1 列用 'A' 表示,第 2 列用 'B' 表示,第 3 列用 'C' 表示,以此类推。
  • <row> 即单元格的行号 r 。第 r 行就用 整数 r 标识。

给你一个格式为 "<col1><row1>:<col2><row2>" 的字符串 s ,其中 <col1> 表示 c1 列,<row1> 表示 r1 行,<col2> 表示 c2 列,<row2> 表示 r2 行,并满足 r1 <= r2c1 <= c2

找出所有满足 r1 <= x <= r2c1 <= y <= c2 的单元格,并以列表形式返回。单元格应该按前面描述的格式用 字符串 表示,并以 非递减 顺序排列(先按列排,再按行排)。

 

示例 1:

输入:s = "K1:L2"
输出:["K1","K2","L1","L2"]
解释:
上图显示了列表中应该出现的单元格。
红色箭头指示单元格的出现顺序。

示例 2:

输入:s = "A1:F1"
输出:["A1","B1","C1","D1","E1","F1"]
解释:
上图显示了列表中应该出现的单元格。 
红色箭头指示单元格的出现顺序。

 

提示:

  • s.length == 5
  • 'A' <= s[0] <= s[3] <= 'Z'
  • '1' <= s[1] <= s[4] <= '9'
  • s 由大写英文字母、数字、和 ':' 组成
lightbulb

解题思路

方法一:模拟

我们直接遍历范围内的所有单元格,将其添加到答案数组中。

时间复杂度 O(m×n)O(m \times n),空间复杂度 O(m×n)O(m \times n),其中 mmnn 分别为行数和列数的取值范围。

1
2
3
4
5
6
7
8
class Solution:
    def cellsInRange(self, s: str) -> List[str]:
        return [
            chr(i) + str(j)
            for i in range(ord(s[0]), ord(s[-2]) + 1)
            for j in range(int(s[1]), int(s[-1]) + 1)
        ]
speed

复杂度分析

指标
时间Depends on the final approach
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    Can the candidate efficiently parse a string to extract multiple pieces of data?

  • question_mark

    Does the candidate account for the sorting requirement, ensuring the correct order of columns and rows?

  • question_mark

    Is the candidate aware of potential edge cases, such as minimal or maximal ranges?

warning

常见陷阱

外企场景
  • error

    Forgetting to properly convert column letters to numeric values, which is critical for looping through columns.

  • error

    Not handling the inclusive nature of the range properly, resulting in missing or extra cells.

  • error

    Failing to consider that Excel columns are alphabetic (A, B, ..., Z, AA, AB, ...) rather than numeric, leading to incorrect column indexing.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Different representations of the input range (e.g., 'A1:B2' vs. 'A1:F5').

  • arrow_right_alt

    Modifying the format of the output (e.g., returning a 2D array instead of a 1D list).

  • arrow_right_alt

    Expanding the problem to support larger or dynamic Excel ranges with more rows/columns.

help

常见问题

外企场景

Excel 表中某个范围内的单元格题解:String-driven solution … | LeetCode #2194 简单