Leetcode::Roman to Integer

point

Design

Big O(time)

Code

class Solution {
public:
    map<char, int> cToValue;
    map<char, int> cToId;

    void init() {
        cToValue['I'] = 1;   cToValue['V'] = 5;
        cToValue['X'] = 10;  cToValue['L'] = 50;
        cToValue['C'] = 100; cToValue['D'] = 500;
        cToValue['M'] = 1000;

        cToId['I'] = 1; cToId['V'] = 2; cToId['X'] = 3;
        cToId['L'] = 4; cToId['C'] = 5; cToId['D'] = 6;
        cToId['M'] = 7;
    }

    int romanToInt(string s) {
        init();
        int ret = 0;
        for(int i = 0; i < (int)s.size(); i++) {
            if (i != (int)s.size() - 1 && cToId[s[i]] < cToId[s[i+1]]) {
                ret += (cToValue[s[i+1]] - cToValue[s[i]]);
                i++;
            } else {
                ret += cToValue[s[i]];
            }
        }
        return ret;
    }
};