1. 程式人生 > >Leetcode 171:Excel表列序號(超詳細的解法!!!)

Leetcode 171:Excel表列序號(超詳細的解法!!!)

給定一個Excel表格中的列名稱,返回其相應的列序號。

例如,

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

示例 1:

輸入: "A"
輸出: 1

示例 2:

輸入: "AB"
輸出: 28

示例 3:

輸入: "ZY"
輸出: 701

解題思路

這是之前問題Leetcode 168:Excel表列名稱(超詳細的解法!!!)的逆變換。很簡單

class Solution
: def titleToNumber(self, s): """ :type s: str :rtype: int """ n, res = len(s), 0 for c in s: n -= 1 res += (ord(c) - 64) * (26**n) return res

一個更pythonic的解法

from functools import reduce
class Solution
: def titleToNumber(self, s): """ :type s: str :rtype: int """ return reduce(lambda x, y : x * 26 + y, [ord(c) - 64 for c in s])

reference:

https://leetcode.com/problems/excel-sheet-column-number/discuss/52107/My-solutions-in-3-languages-does-any-one-have-one-line-solution-in-Java-or-C%2B%2B

我將該問題的其他語言版本新增到了我的GitHub Leetcode

如有問題,希望大家指出!!!