C#LeetCode刷题之#171-Excel表列序号(Excel Sheet Column Number)

版权声明:Iori 的技术分享,所有内容均为本人原创,引用请注明出处,谢谢合作! https://blog.csdn.net/qq_31116753/article/details/82891012

问题

给定一个Excel表格中的列名称,返回其相应的列序号。

例如,

    A -> 1
    B -> 2
    C -> 3
    ...
    Z -> 26
    AA -> 27
    AB -> 28 
    ...

输入: "A"

输出: 1

输入: "AB"

输出: 28

输入: "ZY"

输出: 701

致谢:特别感谢 @ts 添加此问题并创建所有测试用例。


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 
    ...

Input: "A"

Output: 1

Input: "AB"

Output: 28

Input: "ZY"

Output: 701


示例

public class Program {

    public static void Main(string[] args) {
        var s = "ZY";

        var res = TitleToNumber(s);
        Console.WriteLine(res);

        Console.ReadKey();
    }

    private static int TitleToNumber(string s) {
        var res = 0;
        for(int i = s.Length - 1; i >= 0; i--) {
            res += (s[i] - 64) * (int)Math.Pow(26, s.Length - i - 1);
        }
        return res;
    }

}

以上给出1种算法实现,以下是这个案例的输出结果:

701

分析:

显而易见,以上算法的时间复杂度为: O(n) 。

猜你喜欢

转载自blog.csdn.net/qq_31116753/article/details/82891012