Roman to Integer
EasyTop Interview 150 Arrays & HashingAMDYahooIBMWarnermediaVirtusaTinkoffProblem
Roman numerals are written with the letters I=1, V=5, X=10, L=50, C=100, D=500, M=1000.
Letters are usually written from largest to smallest and their values are added.
There is one twist: when a smaller letter comes right before a larger one, it is subtracted instead
(for example IV is 4 and XC is 90). Given a valid Roman numeral s, return its integer value.
Constraints
- 1 ≤ s.length ≤ 15
- s only contains the letters I, V, X, L, C, D, M
- s is a valid Roman numeral with value from 1 to 3999
Examples: pick one to animate
Solutions
TimeO(n)
SpaceO(1)
Time: One pass over s, with O(1) map lookups per letter.
Space: The value table always has 7 entries, regardless of the length of s.
Walk left to right. If the current letter is worth less than the one after it, subtract its value, otherwise
add it. A subtracted letter is exactly the small half of a pair like IV or CM.