【Leetcode】python - [13] Roman to Integer 個人解法筆記

題目出處

13. Roman to Integer

難度

easy

個人範例程式碼 - hashamp 與「照 Roman numerals 運算邏輯」推進

roman_table = {
    "I":1,
    "V":5,
    "X":10,
    "L":50,
    "C":100,
    "D":500,
    "M":1000
}

class Solution:
    def romanToInt(self, s: str) -> int:
        # "IV" 01
        ans = 0
        for i in range(len(s)-1, -1, -1):
            if i < len(s)-1 and roman_table[s[i]] < roman_table[s[i+1]]: # new i is smaller
                ans -= roman_table[s[i]]
            else:
                ans += roman_table[s[i]]

        return ans

最近在練習程式碼本身就可以自解釋的 Coding style,可以嘗試直接閱讀程式碼理解

算法說明

照 Roman numerals 的推算邏輯,我們從最小的位置開始往大的位置推進,
例外情況為:當「小位置的字母 > 大位置的字母」,我們改採減運算,

例如:

  • “IV”:4, I < V, 5 - 1
  • “XL”:40, X < L, 50 - 10

而正常情況為:

  • “VI”: 5 + 1
  • “LX”: 50 + 10

input handling

x

Boundary conditions

用 for 逆向控制範圍

個人範例程式碼 - 雙 hashamp

roman_table = {
    "I":1,
    "V":5,
    "X":10,
    "L":50,
    "C":100,
    "D":500,
    "M":1000
}

combination = {   
    "IV":4,
    "IX":9,
    "XL":40, 
    "XC":90, 
    "CD":400, 
    "CM":900  
}


class Solution:
    def romanToInt(self, s: str) -> int:
        ans = 0
        i = 0
        while i < len(s):
            if i+1 < len(s) and s[i:i+2] in combination:
                ans += combination[s[i:i+2]]                
                i += 2
            else:
                ans += roman_table[s[i]]
                i += 1

        return ans

最近在練習程式碼本身就可以自解釋的 Coding style,可以嘗試直接閱讀程式碼理解

算法說明

先搜尋兩個字,如果兩個字的組合存在,就拿到結果,
如果找不到兩個字,就去一個字的字典找。

input handling

x

Boundary conditions

用 while 控制範圍

Reference