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
- Method1:通过hashmap实现,速度较慢
class Solution {
public int titleToNumber(String s) {
Map<Character, Integer> map = new HashMap<>();
Character c = 'Z';
for(int i = 26; i > 0; i--){
map.put(c, i);
c--;
}
int count = 0;
if(s.length() == 0) return count;
for(int i = 0; i < s.length(); i++){
count = map.get(s.charAt(i)) + count * 26;
}
return count;
}
}
- 一刷中用hashmap唯一的用处就是记录char和int的对应关系,但是我们完全可以通过当前char的数值和A之间的差值+1获得数字。
class Solution {
public int titleToNumber(String s) {
if(s == null || s.length() == 0) return 0;
int result = 0;
for(int i = 0; i < s.length(); i++){
result *= 26;
int c = s.charAt(i) - 'A' + 1;
result += c;
}
return result;
}
}