题目地址:https://leetcode.com/problems/roman-to-integer/
思路:从左到右遍历,把当前字符对应数字累加到结果中,如果当前数比上一个数大,则需要减去上一个数的2倍。
class Solution {
public:
int romanToInt(string s) {
map<char, int> foo;
foo['I'] = 1;
foo['V'] = 5;
foo['X'] = 10;
foo['L'] = 50;
foo['C'] = 100;
foo['D'] = 500;
foo['M'] = 1000;
int result = 0;
int len = s.length();
for (int i=0; i<len; i++) {
result += foo[(s[i])];
if ((i-1 >=0) && (foo[s[i]] - foo[s[i-1]]) > 0) {
result -= 2 * foo[s[i-1]];
}
}
return result;
}
};
Runtime | Memory |
---|---|
12 ms | 10.5 MB |