简繁EN

LeetCodeNo. 100

【LeetCode with Python】 13. Roman to Integer

目錄

題目

原題頁面:https://leetcode.com/problems/roman-to-integer/
題目型別:Math, String
難度評價:Easy
類似題目:(M) Integer to Roman

Given a roman numeral, convert it to an integer.

Input is guaranteed to be within the range from 1 to 3999.


分析

將一個羅馬數值字串轉化為相應的int。
此題跟Integer to Roman有異曲同工之蛋疼,對於不熟悉羅馬數字的童鞋就是一個噩夢。整體來說,羅馬數字中的字元代表的數值大小,一般是從左至右非嚴格遞減的(也就是說可能相鄰的兩個字元相等),然後不停地累加就行了。但如果發生相鄰的兩個元素,左邊的字元比右邊的字元代表的數值小,就需要減去左右這個字元代表的數值。如IV就是5-1=4,所以CIV就是100-1+5=104。
空間複雜度O(N)。時間複雜度O(N)。
注意IV等這類特殊情況。


程式碼

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution:
# @return an integer
def romanToInt(self, s):
digits = { "I":1, "V":5, "X":10, "L":50, "C":100, "D":500, "M":1000 }
len_s = len(s)
num = 0
for i in range(0, len_s - 1):
cur = digits[s[i]]
next = digits[s[i + 1]]
if cur >= next:
num += cur
else:
num -= cur
num += digits[s[len_s - 1]]
return num

本文地址:https://xnerv.wang/zh-tw/leetcode-roman-to-integer/