leetcode-13-字符串题-罗马数字转整数

题目

1.png

解法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
public:
int romanToInt(string s) {
if(s.empty()) return 0;

unordered_map<char, int> hasher{{'I', 1},{'V', 5},{'X', 10},{'L', 50},{'C', 100},{'D', 500},{'M', 1000}};

int res = 0;
for(int i = 0; i < s.size(); ++i){
bool condition = (i+1 < s.size()) && (s[i] == 'I' && (s[i+1] == 'V' || s[i+1] == 'X')) || (s[i] == 'X' && (s[i+1] == 'L' || s[i+1] == 'C')) || (s[i] == 'C' && (s[i+1] == 'D' || s[i+1] == 'M'));

if(condition){
res += hasher[s[i+1]] - hasher[s[i]];
++i;
}else{
res += hasher[s[i]];
}
}

return res;
}
};