题目描述:
Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
思路是对字符串从右往左进行遍历。若s[i]>=s[i-1],则加上该字符代表的数字,else则减去该数字。代码如下:
class Solution {
public:
int romanToInt(string s) {
unordered_map<char, int> roman;
vector<char> chars = { 'I', 'V', 'X', 'L', 'C', 'D', 'M' };
vector<int> nums = { 1, 5, 10, 50, 100, 500, 1000 };
for (int i = 0; i < chars.size(); i++)
roman[chars[i]] = nums[i];
int prev(0), res(0);
for (int i = s.length(); i >= 0; i--){
char c = s[i];
if (roman[c] >= prev)
res += roman[c];
else
res -= roman[c];
prev = roman[c];
}
return res;
}
};