Hi, I come up with a Python code using reduce.
It costs 75ms, but from the distribution detail, I can see someone get even faster Python code.
Can anyone share a faster implementation?
class Solution: # @param s, a string # @return an integer def titleToNumber(self, s): l = list(s) l.insert(0,0) return reduce(lambda x,y: 26*x+ord(y)-64, l)
def titleToNumber(self, s): if len(s) == 1: return ord(s) - 64 return ord(s[-1]) - 64 + self.titleToNumber(s[:-1]) * 26
def titleToNumber(self, s): def _map(ch): chn = ord(ch) assert chn >= ord('A') and chn <= ord('Z') return chn - ord('A') + 1 base = 1 total = 0 constantbase = ord('Z') - ord('A') + 1 for i in range(len(s)): total += _map(s[len(s) - i - 1]) * base base *= constantbase return total
52ms, but I don't think those measurements are good enough such that you can compare it on that level...
Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.