类型:字符串
-
- 罗马数字转整数 💚
https://leetcode-cn.com/problems/roman-to-integer/
❓ 将罗马数字翻译为阿拉伯数字。
💡 从右往左遍历
我们从右往左遍历罗马字符串,如果发现大数左边跟了一个小数的话,其实就是大数减去哪个小数。比如 IV(4),IX(9)。
class Solution: def romanToInt(self, s: str) -> int: index = len(s) - 1 result = 0 lastValue = 0 while index >= 0: c = s[index] if c == 'I': value = 1 elif c == 'V': value = 5 elif c == 'X': value = 10 elif c == 'L': value = 50 elif c == 'C': value = 100 elif c == 'D': value = 500 elif c == 'M': value = 1000 if value < lastValue: lastValue = value value = -value else: lastValue = value result += value index -= 1 return result时间复杂度:O(n),空间复杂度:O(1)