This is a reverse operation of problem 12. We can create map lists like problem 12, and take 1 or 2 characters one time; or we can just use the rule to avoid branch: when we observe an reverse order pair, we subtract double the smaller number. For example, CM represents 900, when we see C we add 100, then when we see M, so we need to add M and subtract 200.
Solution:
# T:O(n) S:O(1)
class Solution:
# @return an integer
def romanToInt(self, s):
numeral_map = {"I": 1, "V": 5, "X": 10, "L": 50, "C":100, "D": 500, "M": 1000}
decimal = 0
for i in xrange(len(s)):
if i > 0 and numeral_map[s[i]] > numeral_map[s[i - 1]]:
decimal += numeral_map[s[i]] - 2 * numeral_map[s[i - 1]]
else:
decimal += numeral_map[s[i]]
return decimal
Run Time: 172 ms
No comments:
Post a Comment