【LeetCode】171. Excel Sheet Column Number Excel表列序号(Easy)(JAVA)
题目地址: https://leetcode.com/problems/excel-sheet-column-number/
题目描述:
Given a column title as appear in an Excel sheet, return its corresponding column number.
For example:
A -> 1
B -> 2
C -> 3
...
Z -> 26
AA -> 27
AB -> 28
...
Example 1:
Input: "A"
Output: 1
Example 2:
Input: "AB"
Output: 28
Example 3:
Input: "ZY"
Output: 701
Constraints:
- 1 <= s.length <= 7
- s consists only of uppercase English letters.
- s is between “A” and “FXSHRXW”.
题目大意
给定一个Excel表格中的列名称,返回其相应的列序号。
解题方法
- Excel 表格的形式, [A, Z] 26 个, [AA, ZZ] 26 * 26 个 … [A…A, Z…Z] 26 * … * 26 个
- 先把 s.length() - 1 个前面的所有个数先加上
- 在计算出 s.length() 前面的个数,比如 BXXXX ,排在 (2 - 1) * 26^4 + XXX 的位置,不断循环计算出当前位置的个数
- note: 要注意不是从 0 开始,是从 1 开始,要在结果上 +1
class Solution {
public int titleToNumber(String s) {
int pro = 1;
int res = 0;
for (int i = 0; i < s.length() - 1; i++) {
pro *= 26;
res += pro;
}
for (int i = 0; i < s.length(); i++) {
res += pro * (s.charAt(i) - 'A');
pro /= 26;
}
return res + 1;
}
}
执行耗时:1 ms,击败了100.00% 的Java用户
内存消耗:38.6 MB,击败了11.79% 的Java用户