My 35 ms C++ solution with O(n) complexity without using map


  • 0
    J

    I want to share my solution without using hash table or map. Just loop the string, look-up with constant complexity of each letter's value and add them to the output. If the current value is greater than the previous one, minus two times of the previous value.

    class Solution {
    public:
        int romanToInt(string s) {
            /*      
            Symbol	I	V	X	L	C	D	M
            Value	1	5	10	50	100	500	1,000
            */
            std::vector<int> symbol_value(int('X')+1);
            symbol_value[int('I')] = 1;
            symbol_value[int('V')] = 5;
            symbol_value[int('X')] = 10;
            symbol_value[int('L')] = 50;
            symbol_value[int('C')] = 100;
            symbol_value[int('D')] = 500;
            symbol_value[int('M')] = 1000;
            int output = 0;
            int previous = 0;
            for(auto x: s)
            {
                int current = symbol_value[int(x)];
                if(current > previous)
                    output += current - 2*previous;
                else
                {
                    output += current;
                }
                previous = current;
            }
            return output;
        }
    };
    

Log in to reply
 

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