LeetCode 13. Roman to Integer (Python3)
はじめに
LeetCode 「13. Roman to Integer」の問題を Python3 で解きました。
問題
問題文
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.
和訳
ローマ数字は、I、V、X、L、C、D、M の 7 つの異なる記号で表されます。
シンボル 値
I 1
V 5
X 10
L 50
C 100
D 500
M 1000
例えば、ローマ数字の2はIIと書きます。これは単に2つの1を足しただけです。12はXIIと書きます。これは単にX + IIです。27はXXVIIと書きます。これはXX + V + IIです。
ローマ数字は通常、左から右へ大きい数字から小さい数字へと書かれます。ただし、4を表す数字はIIIIではありません。代わりに、4はIVと書かれます。これは、5の前に1があるため、それを差し引いて4とするためです。同じ原理が9にも適用され、9はIXと書かれます。差し引きが用いられるのは以下の6つの場合です:
・I を V (5) と X (10) の前に置いて 4 と 9 を作ることができます。
・X を L (50) と C (100) の前に置いて 40 と 90 を作ることができます。
・C を D (500) と M (1000) の前に置いて 400 と 900 を作ることができます。
ローマ数字が与えられたら、それを整数に変換してください。
例
Input: s = "III"
Output: 3
Explanation: III = 3.
Input: s = "LVIII"
Output: 58
Explanation: L = 50, V= 5, III = 3.
Input: s = "MCMXCIV"
Output: 1994
Explanation: M = 1000, CM = 900, XC = 90 and IV = 4.
制約
- 1 <= s.length <= 15
- s contains only the characters ('I', 'V', 'X', 'L', 'C', 'D', 'M').
- It is guaranteed that s is a valid roman numeral in the range [1, 3999].
解答
ローマ数字を変換する問題です。
基本的は対応する数値を足していくのですが、4や9など、差し引きする場合にどう扱うかがポイントです。
ローマ数字は、左から右へ大きい数字から小さい数字へと書かれるので、
ある文字の数値が次の文字の数値よりも小さい場合、差し引きが行われるということになります。
文字列を走査しながら、ある文字が次の文字より小さければ合計から引く、それ以外は足しています。
コード
class Solution:
def romanToInt(self, s: str) -> int:
value_map = {
"I": 1,
"V": 5,
"X": 10,
"L": 50,
"C": 100,
"D": 500,
"M": 1000
}
total = 0
for i in range(len(s)):
value = value_map[s[i]]
if i + 1 < len(s) and value < value_map[s[i+1]]:
total -= value
else:
total += value
return total
計算量
- 時間的計算量:O(n)
- 1文字ずつ走査
- 空間的計算量:O(1)
- 固定のマップを使うだけ
Discussion