LeetCode 题解工作台
Excel 表列序号
给你一个字符串 columnTitle ,表示 Excel 表格中的列名称。返回 该列名称对应的列序号 。 例如: A -> 1 B -> 2 C -> 3 ... Z -> 26 AA -> 27 AB -> 28 ... 示例 1: 输入: columnTitle = "A" 输出: 1 示例 …
2
题型
6
代码语言
3
相关题
当前训练重点
简单 · 数学·string
答案摘要
Excel 表格中的列名称是一种 26 进制的表示方法。例如,"AB" 表示的列序号是 $1 \times 26 + 2 = 28$。 因此,我们可以遍历字符串 `columnTitle`,将每个字符转换为对应的数值,然后计算结果即可。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数学·string 题型思路
题目描述
给你一个字符串 columnTitle ,表示 Excel 表格中的列名称。返回 该列名称对应的列序号 。
例如:
A -> 1 B -> 2 C -> 3 ... Z -> 26 AA -> 27 AB -> 28 ...
示例 1:
输入: columnTitle = "A" 输出: 1
示例 2:
输入: columnTitle = "AB" 输出: 28
示例 3:
输入: columnTitle = "ZY" 输出: 701
提示:
1 <= columnTitle.length <= 7columnTitle仅由大写英文组成columnTitle在范围["A", "FXSHRXW"]内
解题思路
方法一:进制转换
Excel 表格中的列名称是一种 26 进制的表示方法。例如,"AB" 表示的列序号是 。
因此,我们可以遍历字符串 columnTitle,将每个字符转换为对应的数值,然后计算结果即可。
时间复杂度 ,其中 是字符串 columnTitle 的长度。空间复杂度 。
class Solution:
def titleToNumber(self, columnTitle: str) -> int:
ans = 0
for c in map(ord, columnTitle):
ans = ans * 26 + c - ord("A") + 1
return ans
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Look for a candidate who uses a mathematical approach to solve the problem, rather than brute-forcing through all possible values.
- question_mark
The ability to handle the base-26 conversion correctly is key to solving the problem efficiently.
- question_mark
Check if the candidate can identify and explain potential edge cases like the shortest and longest column titles.
常见陷阱
外企场景- error
Candidates may fail to account for the place value when calculating the column number, leading to incorrect results.
- error
Some may treat the problem like a simple string manipulation problem rather than recognizing the base-26 nature of the column title.
- error
Misunderstanding the range of column titles, especially with long titles like 'FXSHRXW', could lead to performance issues.
进阶变体
外企场景- arrow_right_alt
What happens if the column title is in lowercase? (Adjust for case sensitivity.)
- arrow_right_alt
Can this approach be optimized for large strings if we have a maximum length greater than 7 characters?
- arrow_right_alt
How would the problem change if the column titles were in a different base, like base-10?