2 methods solution in python3


  • 0
    I
    class Solution(object):
        def romanToInt(self, s):
            """
            两种解法
            :type s: str
            :rtype: int
            """
            roman_dict = {
                'I': 1,
                'V': 5,
                'X': 10,
                'L': 50,
                'C': 100,
                'D': 500,
                'M': 1000
            }
            value = roman_dict[s[-1]]
            for i in range(1, len(s)):
                if roman_dict[s[-i]] <= roman_dict[s[-i - 1]]:
                    value += roman_dict[s[-i - 1]]
                else:
                    value -= roman_dict[s[-i - 1]]
                    
            # 另一种解法    
            # for i in range(len(s) - 1):
            #     if roman_dict[s[len(s) - i - 1]] <= roman_dict[s[len(s) - i - 2]]:
            #         value += roman_dict[s[len(s) - i - 2]]
            #     else:
            #         value -= roman_dict[s[len(s) - i - 2]]
    
            return value
    

Log in to reply
 

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