iT邦幫忙

0

leetcode with python:13. Roman to Integer

  • 分享至 

  • xImage
  •  

題目:

Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M.

Symbol: Value
I: 1
V: 5
X: 10
L: 50
C: 100
D: 500
M: 1000

For example, 2 is written as II in Roman numeral, just two ones added together. 12 is written as XII, which is simply X + II. The number 27 is written as XXVII, which is XX + V + II.

Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used:

I can be placed before V (5) and X (10) to make 4 and 9.
X can be placed before L (50) and C (100) to make 40 and 90.
C can be placed before D (500) and M (1000) to make 400 and 900.
Given a roman numeral, convert it to an integer.

題目給我們Roman numeral的規定,再給我們字串求出該字串代表的值

整體看下來,這題最為棘手的地方在於這一段:

I can be placed before V (5) and X (10) to make 4 and 9.
X can be placed before L (50) and C (100) to make 40 and 90.
C can be placed before D (500) and M (1000) to make 400 and 900.

但由於我們知道 Roman numeral 符號排列是由大到小
因此有違反的情況便是上面那些特例
於是我們做個條件式判斷就能知道那些特例的位置
又剛好特例們的值=後-前
將其計算後再加到我們要return的值上即可

class Solution:
    def romanToInt(self, s: str) -> int:
        d={"I":1,"V":5,"X":10,"L":50,"C":100,"D":500,"M":1000}
        x=0
        i=0
        while i<len(s):
            if i+1<len(s):
                if d[s[i]]<d[s[i+1]]:
                    x=x+d[s[i+1]]-d[s[i]]
                    i=i+2
                else:
                    x=x+d[s[i]]
                    i=i+1
            else:
                x=x+d[s[i]]
                i=i+1
        return x

注意:特例是兩字一組因此i+2,且要再加條件判斷避免i+1 out of range
最後執行時間48ms(faster than 91.86%)

那我們下題見


圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言