题目:Excel表列序号
给定一个Excel表格中的列名称,返回其相应的列序号。
例如,
A -> 1
B -> 2
C -> 3
...
Z -> 26
AA -> 27
AB -> 28
ZY -> 701
AAA -> 703
-----------------------------------------------------------------------------------------
解法1:字典处理每个字母对应的数值
class Solution(object):
def titleToNumber(self, s):
"""
:type s: str
:rtype: int
"""
dic = {"A": 1, "B": 2, "C": 3, "D": 4, "E": 5,
"F": 6, "G": 7, "H": 8, "I": 9, "J": 10,
"K": 11, "L": 12, "M": 13, "N": 14, "O": 15,
"P": 16, "Q": 17, "R": 18, "S": 19, "T": 20,
"U": 21, "V": 22, "W": 23, "X": 24, "Y": 25,
"Z": 26}
if len(s) == 1:
return dic[s]
res = 0
for i, letter in enumerate(s):
# print(letter)
if i != len(s)-1:
res += dic[letter]*26**(len(s)-i-1)
else:
res += dic[letter]
return res
解法2#:通过ord()函数处理
ord() 函数是 chr() 函数(对于8位的ASCII字符串)或 unichr() 函数(对于Unicode对象)的配对函数,它以一个字符(长度为1的字符串)作为参数,返回对应的 ASCII 数值,或者 Unicode 数值,如果所给的 Unicode 字符超出了你的 Python 定义范围,则会引发一个 TypeError 的异常。
class Solution(object):
def titleToNumber(self, s):
"""
:type s: str
:rtype: int
"""
result = 0
for letter in s:
result = result * 26 + (ord(letter) - ord('A')) + 1
return result
参考:
https://www.runoob.com/python/python-func-ord.html
https://www.cnblogs.com/everfight/p/leetcode_.html