My straightforward Java solution using hashmap


  • 7
    N

    I am quite strange to Roman numeric, I came up with this solution after I referred to Wikipedia. This solution is quite straightforward. Run-time: 452 ms

    public int romanToInt(String s) {
        HashMap<Character, Integer> map = new HashMap<>();
        map.put('I', 1);
        map.put('V', 5);
        map.put('X', 10);
        map.put('L', 50);
        map.put('C', 100);
        map.put('D', 500);
        map.put('M', 1000);
        int len = s.length();
        int index = 0, result = 0;
        while (index < len) {
            Character chCur = s.charAt(index);
            Character chNext = null;
            if (index + 1 < len)
                chNext = s.charAt(index + 1);
            if(chNext != null && map.get(chCur) < map.get(chNext))
                result -= map.get(chCur);
            else
                result += map.get(chCur);
            index++;
        }
        return result;
    }

  • 0
    M

    Can this solution guarantee the output is between 1 and 3999?


  • 0
    N

    If I remember it correctly, the OJ test cases test it all from 1 to 3999, so yes.


  • 0
    R

    Made it more simple and little bit faster

    public class Solution {
        public int romanToInt(String s) {
            int res = 0;
            HashMap<Character,Integer> map = new HashMap<Character,Integer>();
            map.put('I',1);
            map.put('V',5);
            map.put('X',10);
            map.put('L',50);
            map.put('C',100);
            map.put('D',500);
            map.put('M',1000);
            res += map.get(s.charAt(0));
            for(int i=1;i<s.length();i++){
                int cur = map.get(s.charAt(i));
                int pre = map.get(s.charAt(i-1));
                if (pre<cur) res -= pre*2;
                res += cur;
            }
            return res;
        }
    }
    

  • 0
    P

    @NathanLvzs it failed "MMDLV" due to TLE


  • 0
    U

    No need to put so many checks

    public class Solution {
        public int romanToInt(String s) {
            Map<Character, Integer> map = new HashMap<Character, Integer>();
            map.put('I',1);
            map.put('V',5);
            map.put('X',10);
            map.put('L',50);
            map.put('C',100);
            map.put('D',500);
            map.put('M',1000);
            int val=0;
            int preIndex = 0;
            
            for(int i=s.length()-1;i>=0;i--){
                if(map.get(s.charAt(i))<preIndex){
                    val = val - map.get(s.charAt(i));
                }else{
                    val = val + map.get(s.charAt(i));
                }
                preIndex = map.get(s.charAt(i));
            }
            
            return val;
            
        }
    }
    

Log in to reply
 

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