给定一个Excel表格中的列名称,返回其相应的列序号。
例如,
A -> 1
B -> 2
C -> 3
...
Z -> 26
AA -> 27
AB -> 28
...
示例 1:
输入: “A”
输出: 1
示例 2:
输入: “AB”
输出: 28
示例 3:
输入: “ZY”
输出: 701
我的思路:首先放入到hashmap中,之后需要取出就是进行26进制的计算
public static int titleToNumber(String s) {
Map<String,Integer> hash = new HashMap<>();
hash.put("A",1);
hash.put( "B",2);
hash.put( "C",3);
hash.put( "D",4);
hash.put( "E",5);
hash.put( "F",6);
hash.put( "G",7);
hash.put( "H",8);
hash.put( "I",9);
hash.put( "J",10);
hash.put( "K",11);
hash.put( "L",12);
hash.put( "M",13);
hash.put( "N",14);
hash.put( "O",15);
hash.put( "P",16);
hash.put( "Q",17);
hash.put( "R",18);
hash.put( "S",19);
hash.put( "T",20);
hash.put( "U",21);
hash.put( "V",22);
hash.put( "W",23);
hash.put( "X",24);
hash.put( "Y",25);
hash.put( "Z",26);
StringBuilder sb = new StringBuilder(s);
StringBuilder sb2 = sb.reverse();
String s3 = sb.toString();
char [] s1 = s3.toCharArray();
int sum = 0;
for (int i = 0; i < s1.length; i++) {
String c = s1[i] + "";
sum += Math.pow(26,i) * hash.get(c);
}
return sum;
}
排名比较高的比较高的代码
class Solution {
public int titleToNumber(String s) {
int res = 0;
for(int i=0;i<s.length();i++){
int temp = s.charAt(i)-'A'+1;
res = res*26+temp;
}
return res;
}
}