LeetCode 13. 罗马数字转整数 Roman to Integer

时间复杂度:O(N)空间复杂度:O(1)

class Solution {
public:
    int romanToInt(string s) {
        int res = 0;
        map<char, int> roman = 
        {   {'I', 1},
            {'V', 5},
            {'X', 10},
            {'L', 50},
            {'C', 100},
            {'D', 500},
            {'M', 1000} };
        for (int i = 0; i < s.size(); ++i)
        {
            if (roman[s[i]] < roman[s[i + 1]])  //特殊情况
                res -= roman[s[i]];
            else
                res += roman[s[i]];
        }
        return res;
    }
};

猜你喜欢

转载自www.cnblogs.com/ZSY-blog/p/12951485.html
今日推荐