My O(n) Java Solution


  • 0
    T
    public class Solution {
        public int romanToInt(String s) {
            int back = 0;
            int curr = 0;
            int result = 0;
            for (int i = 0; i < s.length(); i++) {
                curr = back;
                back = convertToInt(s.charAt(i));
                if (curr < back) curr = -curr;
                result += curr;
            }
            result += back;
            return result;
        }
        public int convertToInt(char c) {
            int result = 0;
            switch (c) {
                case 'L': result = 50; break;
                case 'D': result = 500; break;
                case 'M': result = 1000; break;
                case 'X': result = 10; break;
                case 'I': result = 1; break;
                case 'V': result = 5; break;
                case 'C': result = 100; break;
            }
            return result;
        }
    }
    

Log in to reply
 

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