13. Roman to Integer

Solution

/**
 * @param {string} s
 * @return {number}
 */
 var romanToInt = function(s) {
    const values = {
        "I": 1,
        "V": 5,
        "X": 10,
        "L": 50,
        "C": 100,
        "D": 500,
        "M": 1000
    }
    
    const map = {
        "V": "I",
        "X": "I",
        "L": "X",
        "C": "X",
        "D": "C",
        "M": "C",
    }
    
    let result = 0;
    
    for (let i = s.length - 1; i >= 0; i--) {
        result += values[s[i]];

        if (i >= 1) {
            if (s[i - 1] === map[s[i]]) {
                result -= values[map[s[i]]];
                i--;
            }
        }
    }
    
    return result;
};

Complexity

  • Time Complexity: O(N), where N is the size of s.
  • Space Complexity: O(1).

All Solutions