O(n) Time and O(1) space


  • 0
    D

    This is an alternate solution that I felt was a good one. Got 87+ percentile speed.

    public class Solution {
    public int romanToInt(String s) {
    if(s.equals("")) {
    return 0;
    }
    int sum = 0;
    s = s.toUpperCase();

        int myLength = s.length();
        
        int val1 = convert(s.charAt(0));
        for(int i = 1 ; i < myLength ; i++) {
            int val2 = convert(s.charAt(i));
            
            if(val1 < val2) {
                sum -= val1;
            } else {
                sum += val1;
            }
            
            val1 = val2;
        }
        
        sum += convert(s.charAt(myLength - 1));
        
        return sum;
    }
    
    private int convert(char roman) {
        switch(roman) {
            case 'I': return 1;
            case 'V': return 5;
            case 'X': return 10;
            case 'L': return 50;
            case 'C': return 100;
            case 'D': return 500;
            default: return 1000;
        }
    }
    

    }


Log in to reply
 

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