forked from shuboc/LeetCode-2
-
Notifications
You must be signed in to change notification settings - Fork 1
/
roman-to-integer.cpp
36 lines (34 loc) · 1.26 KB
/
roman-to-integer.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
// Time: O(n)
// Space: O(1)
class Solution {
public:
int romanToInt(string s) {
unordered_map<char, int> numeral_map = {{'I', 1}, {'V', 5}, {'X', 10},
{'L', 50}, {'C', 100}, {'D', 500},
{'M', 1000}};
int decimal = 0;
for (int i = 0; i < s.length(); ++i) {
if (i > 0 && 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;
}
};
// Time: O(n)
// Space: O(1)
class Solution2 {
public:
int romanToInt(string s) {
unordered_map<char, int> numeral_map = {{'I', 1}, {'V', 5}, {'X', 10},
{'L', 50}, {'C', 100}, {'D', 500},
{'M', 1000}};
return accumulate(s.crbegin(), s.crend(), 0,
[&numeral_map](int sum , char c) {
return sum += ((numeral_map[c] * 5 <= sum) ?
-numeral_map[c] : numeral_map[c]);
});
}
};