An elegant and simple Java solution


  • 0
    L

    The idea is to move from left to right in the string and do the best match. It will not work when you do from right to left. For example "XLI" requires you to go from left to right. Always try to match 2 characters first and then fall back to 1 if things don't work out. Here is the code:

        private static final Map<String,Integer> map = new HashMap<>();
        static {
            map.put("M",1000);
            map.put("CM",900);
            map.put("D",500);
            map.put("CD",400);
            map.put("C",100);
            map.put("XC",90);
            map.put("L",50);
            map.put("XL",40);
            map.put("X",10);
            map.put("IX",9);
            map.put("V",5);
            map.put("IV",4);
            map.put("I",1);
        }
        public int romanToInt(String s) {
            //"XLI"
            int val = 0;
            if(s.isEmpty()) {
                return val;
            }
            int i=0;
            while(i<s.length()) {
                if((i+1)<s.length()) {
                    String roman = s.substring(i,i+2);
                    if(map.containsKey(roman)) {
                        val += map.get(roman);
                        i +=2;
                        continue;
                    }
                }
                val += map.get(s.substring(i,i+1));
                i++;
            }
            return val;
        }
    

Log in to reply
 

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