Sharing my 84ms C++ solution using hash table


  • 0
    T
    class Solution {
    public:
        int romanToInt(string s) {
            unordered_map<char, int> myMap;
            myMap.insert({'I', 1});
            myMap.insert({'V', 5});
            myMap.insert({'X', 10});
            myMap.insert({'L', 50});
            myMap.insert({'C', 100});
            myMap.insert({'D', 500});
            myMap.insert({'M', 1000});
            
            int n = s.length();
            int i;
            int sum = myMap[s[n-1]];
            for(i=n-2; i>=0; i--)
            {
                if(myMap[s[i]] < myMap[s[i+1]])
                    sum = sum-myMap[s[i]];
                else
                    sum = sum+myMap[s[i]];
            }
            
            return sum;
        }
    };

Log in to reply
 

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