原文:http://topic.csdn.net/u/20080923/11/ee117de0-38ec-4d34-802d-64c7a0f34b7f.html
序列Seq=[a,b,…z,aa,ab…az,ba,bb,…bz,…,za,zb,…zz,aaa,…] 类似与excel的排列,任意给出一个字符串s=[a-z]+(由a-z字符组成的任意长度字符串),请问s是序列Seq的第几个
火龙果:
A: 1
B: 2
...
Z: 26
AA = 1 * 26^1 + 1 = 27
AAA = 1 * 26^2 + 1 * 26^1 + 1 = 703
将字母序列从右往左依次编号为 i,最右边一位为 0,最左边一位为 n,
在 i 位上字母的值为 K[i],则序列为:
相当于26进制。
- public class T {
- public static void main(String[] args) {
- int n = letter2Number("ab");
- System.out.println(n);
- }
- public static int letter2Number(String letters) {
- if (!letters.matches("[a-zA-Z]+")) {
- throw new IllegalArgumentException("Format ERROR!");
- }
- char[] chs = letters.toLowerCase().toCharArray();
- int result = 0;
- for (int i = chs.length - 1, p = 1; i >= 0; i--) {
- result += getNum(chs[i]) * p;
- p *= 26;
- }
- return result;
- }
- private static int getNum(char c) {
- return c - 'a' + 1;
- }
- }