O(n) Javascript solution using hash


  • 0
    B
    var romanToInt = function(s) {
        var map = {
        	'I': 1,
            'V': 5,
            'X': 10,
            'L': 50,
            'C': 100,
            'D': 500,
            'M': 1000,
            'IV': 4,
            'IX': 9,
            'XL': 40,
            'XC': 90,
            'CD': 400,
            'CM': 900
        };
        
        var value = 0;
        for (var i=0; i<s.length; i++) {
            if (i+1 !== s.length) {
                var t = s[i] + s[i+1];
                if (map[t]) {
                    value += map[t];
                    i++;
                	continue;
                }
            }
            
            value += map[s[i]];
        }
        return value;
    };
    

Log in to reply
 

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