1、用hashtable
class Solution {
public:
int romanToInt(string s) {
int result = 0;
string temp;
unordered_map<string, int>hashtable{
{"I", 1}, {"V", 5}, {"X", 10}, {"L", 50}, {"C", 100},
{"D", 500}, {"M", 1000}, {"IV", 4}, {"IX", 9}, {"XL", 40},
{"XC", 90}, {"CD", 400}, {"CM", 900}
};
for(int i=0; i<s.size(); i++){
temp = s[i];
if(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')){
temp += s[i+1];
i++;
}
result += hashtable[temp];
}
return result;
}
};
2、官方,找出规律,处理特殊数字的时候更为简单,如IV、IX这种左边数字比右边小的就改成减。
class Solution {
private:
unordered_map<char, int> symbolValues = {
{'I', 1},
{'V', 5},
{'X', 10},
{'L', 50},
{'C', 100},
{'D', 500},
{'M', 1000},
};
public:
int romanToInt(string s) {
int ans = 0;
int n = s.length();
for (int i = 0; i < n; ++i) {
int value = symbolValues[s[i]];
if (i < n - 1 && value < symbolValues[s[i + 1]]) {
ans -= value;
} else {
ans += value;
}
}
return ans;
}
};