map

1
2
3
4
5
6
7
8
9
10
class Solution {
public:
int romanToInt(string s) {
unordered_map<char,int> m = {{'I',1}, {'V',5}, {'X',10},{'L',50},{'C',100}, {'D',500},{'M',1000}};
int sum = 0;
for(int i = 0 ; i < s.size(); ++i)
m[s[i]] < m[s[i+1]] ? sum -= m[s[i]]: sum += m[s[i]];
return sum;
}
};

数组(效率很高)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
public:
int romanToInt(string s) {
int m[90] = {};
m['I'] = 1;
m['V'] = 5;
m['X'] = 10;
m['L'] = 50;
m['C'] = 100;
m['D'] = 500;
m['M'] = 1000;
int sum = 0;
for(int i = 0 ; i < s.size(); ++i)
m[s[i]] < m[s[i+1]] ? sum -= m[s[i]]: sum += m[s[i]];
return sum;
}
};