My Java solution with O(1) space


  • 0
    M

    Add some corner cases while I was understanding this Roman calculation.

        public int romanToInt(String s) {
            if (s == null || s.length() == 0) {
                return 0;
            }
            // directly return the value if the length is 1
            if (s.length() == 1) {
                return helper(s.charAt(0));
            }
            // find the first valid index ("--VII")
            int index = 0;
            while (index < s.length() && helper(s.charAt(index)) == 0) {
                index++;
            }
            // case "--" should return 0
            if (index >= s.length()) {
                return 0;
            }
    
            index = index + 1;
            int sum = 0;
            int cur = 0, next = 0;
    
            while (index < s.length()) {
                cur = helper(s.charAt(index - 1));
                next = helper(s.charAt(index));
    
                if (cur < next) {
                    sum -= cur;
                } else {
                    sum += cur;
                }
                index++;
            }
            sum += next;
    
            return sum;
        }
    
        private int helper(char ch) {
            switch (ch) {
                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;
            }
    
            return 0;
        }
    

Log in to reply
 

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