O(n) time, O(1) space, easy to understand, cleaner, runs faster than 94% of the submissions


  • 0
        public int romanToInt(String s) {
            if(s.isEmpty()) return 0;
            
            int sum = 0, prevValue = 0, n=s.length();
            
            for(int i=n-1; i>=0; i--){
                char focus = s.charAt(i);
                int value = getValue(focus);
                if(prevValue > value)
                    sum -= value;
                else
                    sum += value;
                
                prevValue = value;    
            }
            
            return sum;
        }
        
        public int getValue(char c){
            switch(Character.toUpperCase(c)){
                case 'I': return 1;
                case 'V': return 5;
                case 'X': return 10;
                case 'L': return 50;
                case 'C': return 100;
                case 'D': return 500;
                case 'M': return 1000;
                default: return 0;
            }
        }
    

Log in to reply
 

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