C++ lookup table solution


  • 0
    J

    The code is not that fast 60ms, but I think the overhead of creating the look up table is big..

    class Solution {
    public:
        int romanToInt(string s) {
            int size = s.length();
            std::map<char, int> number_lookup;
            number_lookup.insert(std::pair<char,int>('I', 1));
            number_lookup.insert(std::pair<char,int>('V', 5));
            number_lookup.insert(std::pair<char,int>('X', 10));
            number_lookup.insert(std::pair<char,int>('L', 50));
            number_lookup.insert(std::pair<char,int>('C', 100));
            number_lookup.insert(std::pair<char,int>('D', 500));
            number_lookup.insert(std::pair<char,int>('M', 1000));
            
            int prev_val = number_lookup[s[size - 1]];
            int result = prev_val;
            for (int i = size - 2; i >= 0; --i) {
                int current_val = number_lookup[s[i]];
                if (current_val < prev_val) {
                    result -= current_val;
                } else {
                    result += current_val;
                }
                prev_val = current_val;
            }
            return result;
        }
    };

  • 0
    E

    My first thought is using map too, but it turns out using switch is faster for such small size table.


Log in to reply
 

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