C++
class Solution {
public:
int romanToInt(string s) {
int n = s.length(), ans = 0;
unordered_map<char, int> map;
map['I'] = 1, map['V'] = 5;
map['X'] = 10, map['L'] = 50;
map['C'] = 100, map['D'] = 500;
map['M'] = 1000;
for (int i = 0; i < n; i++) {
if (i < n - 1 && map[s[i]] < map[s[i + 1]])
ans -= map[s[i]];
else
ans += map[s[i]];
}
return ans;
}
};
Python3
class Solution:
def romanToInt(self, s: str) -> int:
dic = {'I':1, 'V':5, 'X':10, 'L':50, 'C':100, 'D':500, 'M':1000}
ans = 0
n = len(s)
for i in range(n):
if i < n - 1 and dic[s[i]] < dic[s[i + 1]]:
ans -= dic[s[i]]
else:
ans += dic[s[i]]
return ans
Go
func romanToInt(s string) int {
n := len(s)
ans := 0
myMap := map[byte]int {
'I':1, 'V':5,
'X':10, 'L':50,
'C':100, 'D':500,
'M':1000,
}
for i := 0; i < n; i++ {
if i < n - 1 && myMap[s[i]] < myMap[s[i + 1]] {
ans -= myMap[s[i]]
} else {
ans += myMap[s[i]]
}
}
return ans
}