Leetcode # 13. Roman to Integer

https://leetcode.com/problems/roman-to-integer

Solution

Time Complexity: O(len(s))
Space Complexity: O(1)
(The input and output generally do not count towards the space complexity.)

class Solution:
  def romanToInt(self, s: str) -> int:
    roman = [
      [ "I",    1], 
      ["IV",    4], 
      [ "V",    5], 
      ["IX",    9], 
      [ "X",   10], 
      ["XL",   40], 
      [ "L",   50], 
      ["XC",   90], 
      [ "C",  100], 
      ["CD",  400], 
      [ "D",  500], 
      ["CM",  900], 
      [ "M", 1000]
    ]

    r_i, s_i = 0, len(s)
    num = 0
    while s_i > 0 and r_i < len(roman):
      if s[0:s_i].endswith(roman[r_i][0]):
        num += roman[r_i][1]
        s_i -= len(roman[r_i][0]) # !!!
      else:
        r_i += 1

    return num

 

Last Updated on 2023/08/16 by A1go

目錄

目錄
Bitnami