171. Excel 表列序号
题目描述
输入字符串 columnTitle,它是 Excel 表格的列名,只含大写字母。返回这一列的序号。
编号规则:A 到 Z 依次对应 1 到 26;AA 对应 27,AB 对应 28,依此类推。
示例 1
输入:columnTitle = "A" 输出:1
解释:A 是第 1 列。
示例 2
输入:columnTitle = "AB" 输出:28
解释:AB = 1 × 26 + 2 = 28。
示例 3
输入:columnTitle = "ZY" 输出:701
解释:ZY = 26 × 26 + 25 = 701。
数据范围
1 <= columnTitle.length <= 7columnTitle只含大写英文字母。columnTitle介于"A"与"FXSHRXW"之间。
解题思路
把列名看成每位取值 1–26 的 26 进制数,从高位到低位扫描(秦九韶法):每读到一个字母,就把已有结果乘 26(整体左移一位),再加上这个字母的值 ord(ch) - ord("A") + 1。
为什么正确
处理完前 k 个字母后,ans 等于前缀 columnTitle[:k] 所代表的列序号。
复杂度分析
时间 O(n),n 为字符串长度;空间 O(1)。
易错点
字母值是 ord(ch) - ord("A") + 1,不要忘了 +1(A 是 1 不是 0)。中间结果在其他语言里可能接近 int 上限,用 long 更稳妥。
参考代码
Python、Java、C++、Go、JavaScript、TypeScript 六种语言,逻辑一致。
class Solution:
def titleToNumber(self, columnTitle: str) -> int:
ans = 0
for ch in columnTitle:
d = ord(ch) - ord('A') + 1
ans = ans * 26 + d
return ansclass Solution {
public int titleToNumber(String columnTitle) {
long ans = 0;
for (char ch : columnTitle.toCharArray()) {
int d = ch - 'A' + 1;
ans = ans * 26 + d;
}
return (int) ans;
}
}class Solution {
public:
int titleToNumber(string columnTitle) {
long long ans = 0;
for (char ch : columnTitle) {
int d = ch - 'A' + 1;
ans = ans * 26 + d;
}
return (int)ans;
}
};func titleToNumber(columnTitle string) int {
ans := 0
for _, ch := range columnTitle {
d := int(ch-'A') + 1
ans = ans*26 + d
}
return ans
}var titleToNumber = function(columnTitle) {
let ans = 0;
for (const ch of columnTitle) {
const d = ch.charCodeAt(0) - 64;
ans = ans * 26 + d;
}
return ans;
};function titleToNumber(columnTitle: string): number {
let ans = 0;
for (const ch of columnTitle) {
const d = ch.charCodeAt(0) - 64;
ans = ans * 26 + d;
}
return ans;
}