题解
特殊情况:
我最初的做法是 使用map保存单个字符和值的映射,对于题目中描述的特殊情况进行判断,若为特殊情况则特殊处理。
一个更好的方法是将map做成string到int值的映射,这样对于IV,XL,CD等便可以直接给出映射值。
我的代码
class Solution {
public:
int romanToInt(string s) {
map<char, int> mp;
mp['I'] = 1;mp['V'] = 5;mp['X'] = 10;mp['L'] = 50;
mp['C'] = 100;mp['D'] = 500;mp['M'] = 1000;
int res = mp[s[0]], cnt = 0;
int len = s.length();
for (int i = 1;i < len;i++) {
int now = mp[s[i]];
int temp = now - 2 * mp[s[i - 1]];
if (temp == 3 || temp == 8 || temp == 30 || temp == 80 || temp == 300 || temp == 800)
res += temp;
else
res += now;
}
return res;
}
};
参考代码
class Solution {
public:
int romanToInt(string s) {
unordered_map<string, int> m = {{"I", 1}, {"IV", 3}, {"IX", 8}, {"V", 5}, {"X", 10}, {"XL", 30}, {"XC", 80}, {"L", 50}, {"C", 100}, {"CD", 300}, {"CM", 800}, {"D", 500}, {"M", 1000}};
int r = m[s.substr(0, 1)];
for(int i=1; i<s.size(); ++i){
string two = s.substr(i-1, 2);
string one = s.substr(i, 1);
r += m[two] ? m[two] : m[one];
}
return r;
}
};