leetcode解题: Roman to Integer (13)

Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.

解法1:O(N) Time

Roman to Integer 是较容易的。需要记忆的是几个关键的Roman字母和数值的对应关系。
从后往前扫描,如果前面的数值比后面的数值小,则需要减去,否则加上。

1
2
3
| I | V | X | L | C | D | M |
|---|---|----|---|---|---|--- |
| 1 | 5 | 10 |50 |100|500|1000|

C++

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
public:
int romanToInt(string s) {
if (s.empty()) {
return 0;
}
int res = 0;
res += romans[toupper(s[s.size() - 1])];
for (int i = s.size() - 2; i >= 0; --i) {
if (romans[toupper(s[i])] < romans[toupper(s[i + 1])]) {
res -= romans[toupper(s[i])];
} else {
res += romans[toupper(s[i])];
}
}
return res;
}
private:
unordered_map<char, int> romans {{'I',1},{'V',5},{'X',10}, {'L',50}, {'C', 100}, {'D',500}, {'M',1000}};
}
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
class Solution {
public int romanToInt(String s) {
Map<Character, Integer> map = new HashMap<>();
map.put('I', 1);
map.put('V', 5);
map.put('X', 10);
map.put('L', 50);
map.put('C', 100);
map.put('D', 500);
map.put('M', 1000);
int res = 0;
res += map.get(s.charAt(s.length() - 1));
for (int i = s.length() - 2; i >= 0; i--) {
int current = map.get(s.charAt(i));
int last = map.get(s.charAt(i + 1));
if (current < last) {
res -= current;
} else {
res += current;
}
}
return res;
}
}