Sunday, September 7, 2014

Leetcode: Roman to Integer @Python

class Solution:
    # @return an integer
    def romanToInt(self, s):
        roman_numeral_map = (('M',  1000),('CM', 900),('D',  500),('CD', 400),('C',  100),('XC', 90),('L',  50),('XL', 40),('X',  10),('IX', 9),('V',  5),('IV', 4),('I',  1))
        rst=0
        index=0
        #pattern='^M{0,3}(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})$'
        #if not re.search(pattern,s): return None
        for roman, numeral in roman_numeral_map:
            while s[index:index+len(roman)]==roman:
                rst+=numeral
                index+=len(roman)
        return rst

No comments :

Post a Comment