问题
Related to question Excel Sheet Column Title
Given a column title as appear in an Excel sheet, return its corresponding column number.
例子
A -> 1
B -> 2
C -> 3
...
Z -> 26
AA -> 27
AB -> 28
分析
字符映射,逐字符遍历字符串,然后转成1-26即可。之前的结果在下一轮循环中乘26.
要点
字符映射
时间复杂度
O(n)
空间复杂度
O(1)
代码
class Solution {
public:
int titleToNumber(string s) {
int res = 0, n = s.size();
for (int i = 0; i < n; i++) {
res = res * 26 + s[i] - 'A' + 1;
}
return res;
}
};