LeetCode 题解工作台

Excel 表列序号

给你一个字符串 columnTitle ,表示 Excel 表格中的列名称。返回 该列名称对应的列序号 。 例如: A -> 1 B -> 2 C -> 3 ... Z -> 26 AA -> 27 AB -> 28 ... 示例 1: 输入: columnTitle = "A" 输出: 1 示例 …

category

2

题型

code_blocks

6

代码语言

hub

3

相关题

当前训练重点

简单 · 数学·string

bolt

答案摘要

Excel 表格中的列名称是一种 26 进制的表示方法。例如,"AB" 表示的列序号是 $1 \times 26 + 2 = 28$。 因此,我们可以遍历字符串 `columnTitle`,将每个字符转换为对应的数值,然后计算结果即可。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 数学·string 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个字符串 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 <= 7
  • columnTitle 仅由大写英文组成
  • columnTitle 在范围 ["A", "FXSHRXW"]
lightbulb

解题思路

方法一:进制转换

Excel 表格中的列名称是一种 26 进制的表示方法。例如,"AB" 表示的列序号是 1×26+2=281 \times 26 + 2 = 28

因此,我们可以遍历字符串 columnTitle,将每个字符转换为对应的数值,然后计算结果即可。

时间复杂度 O(n)O(n),其中 nn 是字符串 columnTitle 的长度。空间复杂度 O(1)O(1)

1
2
3
4
5
6
7
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
speed

复杂度分析

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

面试官常问的追问

外企场景
  • 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.

warning

常见陷阱

外企场景
  • 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.

swap_horiz

进阶变体

外企场景
  • 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?

help

常见问题

外企场景

Excel 表列序号题解:数学·string | LeetCode #171 简单