Leetcode One Question of the Day 202.25 Question 13: Converting Roman Numerals to Integers

Title description

Insert picture description here

Example

Insert picture description here

Ideas

Through observation, we found that among the two characters,

  • When left character <right character, = number of characters on the right-number of characters on the left
  • When the left character >= the right character, = the number of characters on the right + the number of characters on the left

algorithm

We store the corresponding relationship in the Roman2Int hash table in the form of {character: number}, and then traverse each character from left to right. If s[i] <s[i+1], subtract s[ from the result The number represented by i]; otherwise, the number represented by s[i] is added to the result. And the number represented by the last character must be added to the result.

Code

class Solution:
    def romanToInt(self, s: str) -> int:
        Roman2Int = {
    
    'I':1, 'V':5, 'X':10, 'L':50, 'C':100, 'D':500, 'M':1000}
        Int = 0
        n = len(s)
        for index in range(n-1):
            if Roman2Int[s[index]] < Roman2Int[s[index+1]]:
                Int -= Roman2Int[s[index]]
            else:
                Int += Roman2Int[s[index]]
        Int += Roman2Int[s[-1]]
        return Int 

Guess you like

Origin blog.csdn.net/m0_51210480/article/details/114093263