solution in Python using dict


  • 1
    T

    Using dict will be easy to understand.

    class Solution(object):
        def titleToNumber(self, s):
            """
            :type s: str
            :rtype: int
            """
            table = {'R': 18, 'V': 22, 'K': 11, 'A': 1, 'I': 9, 'F': 6, 'X': 24, 'Q': 17, 'E': 5, 'D': 4, 'B': 2, 'Y': 25, 'S': 19, 'L': 12, 'J': 10, 'H': 8, 'U': 21, 'T': 20, 'C': 3, 'Z': 26, 'O': 15, 'N': 14, 'W': 23, 'M': 13, 'G': 7, 'P': 16}
            col_num = 0
            for i in s:
                col_num = col_num * 26 + table[i]
            return col_num
    

    How to generate the dict:

    table = {}
    index = 1
    for i in 'abcdefghijklmnopqrstuvwxyz':
        table[i.upper()] = index
        index += 1
    

  • 0
    F

    That's unnecessary. Just

            r = 0
            for c in s:
                r *= 26
                r += ord(c) - ord('A') + 1
            return r
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.