My short recursive solution


  • 0
    class Solution {
    private:
        map<char, int> mapping;
        string romanString;
    public:
        int romanToInt(string s) {
            romanString = s;
            mapping['I'] = 1;
            mapping['V'] = 5;
            mapping['X'] = 10;
            mapping['L'] = 50;
            mapping['C'] = 100;
            mapping['D'] = 500;
            mapping['M'] = 1000;
            return helper(0);
        }
        int helper(int i) {
            if(i == romanString.size()) return 0;
            if(i == romanString.size() - 1) {
                return mapping[romanString[i]];
            }
            if(mapping[romanString[i]] >= mapping[romanString[i+1]]){
                return mapping[romanString[i]] + helper(i+1);
            }
            return mapping[romanString[i+1]] - mapping[romanString[i]] + helper(i+2);
        }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.