[LeetCode] Top Interview 150 Problems Solving # 13 Roman to Integer
Understanding the Problem
The problem is direct and very simply understandable. Changing roman number to integer and returning the integer is the only task.
But it is quite tricky when it comes to the combination of the numbers.
# basic roman numbers
Symbol Value
I 1
V 5
X 10
L 50
C 100
D 500
M 1000
The tricks that I had checked from the instruction was three.
I
can be placed beforeV
(5) andX
(10) to make 4 and 9.X
can be placed beforeL
(50) andC
(100) to make 40 and 90.C
can be placed beforeD
(500) andM
(1000) to make 400 and 900.
Approach
Hash map was the solution that I had thought about. I would build the hash map for the basic roman numbers for the single characters, then another hash map for the combinations.
# combination
nums = {
"IV":4,
"IX":9,
"XL":40,
"XC":90,
"CD":400,
"CM":900
}
# single characters
symbols = {
"I":1,
"V":5,
"X":10,
"L":50,
"C":100,
"D":500,
"M":1000
}
With the two hash maps, I would just need to for
loop.
Solution
class Solution:
def romanToInt(self, s: str) -> int:
nums = {
"IV":4,
"IX":9,
"XL":40,
"XC":90,
"CD":400,
"CM":900
}
symbols = {
"I":1,
"V":5,
"X":10,
"L":50,
"C":100,
"D":500,
"M":1000
}
total = 0
# checking subtracts
for k, v in nums.items():
while k in s:
s = s.replace(k, "")
total += v
# replacing single nums
for c in s:
total += symbols[c]
return total
I was using total
to get the sum from the roman numbers.
First thing was to get key as
k
and value asv
fromnums
for the combination calculation while iterating the hash map, then check in thewhile
loop thek
. If it includes thek
, value(v
) will be added to total and replace the key so it will not be again used to calculate integer.In another
for
loop in thes
, just as simple as that, I check each character(c
) then add the corresponding number tototal
Just returned total as integer
Reflection
This was somehow not as hard as I thought it would be. But if I have to think about the efficiency, it is not as good as it should be(still better than many others on LeetCode). The complexity will go nearly O(2n²). Others did it with O(n), looping with only one time for
char by char, comparing current index value with the previous value. Well, this is some rule that I did not know of. Something new to learn today as well.