13. Roman to Integer

题目地址:https://leetcode.com/problems/roman-to-integer/
思路:从左到右遍历,把当前字符对应数字累加到结果中,如果当前数比上一个数大,则需要减去上一个数的2倍。

class Solution {
public:
    int romanToInt(string s) {
        map 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=0) && (foo[s[i]] - foo[s[i-1]]) > 0) {
                result -= 2 * foo[s[i-1]];
            }
        }
        return result;
    }
};
Runtime Memory
12 ms 10.5 MB

你可能感兴趣的:(13. Roman to Integer)