40Excel表列序号
2020-08-19 本文已影响0人
Jachin111
给定一个Excel表格中的列名称,返回其相应的列序号。
例如,
A -> 1
B -> 2
C -> 3
...
Z -> 26
AA -> 27
AB -> 28
...
示例 1:
输入: "A"
输出: 1
示例 2:
输入: "AB"
输出: 28
示例 3:
输入: "ZY"
输出: 701
二十六进制转十进制
class Solution:
def titleToNumber(self, s: str) -> int:
res = 0
bit = 1
for a in s[::-1]:
res += (ord(a) - 64) * bit
bit *= 26
return res
哈希表
class Solution:
def titleToNumber(self, s: str) -> int:
d = len(s)
value = 0
sdict = {}
for i in range(1, 27):
sdict[chr(i+64)] = i
for i in s:
if d > 0:
value += sdict[i] * 26**(d-1)
d -= 1
return value
import functools
class Solution:
def titleToNumber(self, s: str) -> int:
return functools.reduce(lambda x, y: x * 26 + y, [ord(a) - 64 for a in s ])
class Solution:
def titleToNumber(self, s: str) -> int:
return sum( (ord(a) - 64) * (26 ** i) for i, a in enumerate(s[::-1]))
来源:力扣(LeetCode)