Java HashMap and Array solutions.


  • 0
    C
    public int romanToInt1(String s) {
        Character[] r = {'I', 'V', 'X', 'L', 'C', 'D', 'M'};
        List<Character> roman = new ArrayList<>(Arrays.asList(r));
        Integer[] n = {1, 5, 10, 50, 100, 500, 1000};
        List<Integer> nums = new ArrayList<>(Arrays.asList(n));
        int ret = nums.get(roman.indexOf(s.charAt(s.length()-1)));
        for (int i=0; i<s.length()-1; i++) {
            if (roman.indexOf(s.charAt(i)) < roman.indexOf(s.charAt(i+1)))
                ret -= nums.get(roman.indexOf(s.charAt(i)));
            else
                ret += nums.get(roman.indexOf(s.charAt(i)));
        }
        return ret;
    }
    
    public int romanToInt(String s) {
        Map<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 ret = map.get(s.charAt(s.length()-1));
        for (int i=0; i<s.length()-1; i++) {
            if(map.get(s.charAt(i)) < map.get(s.charAt(i+1)))
                ret -= map.get(s.charAt(i));
            else
                ret += map.get(s.charAt(i));
        }
        return ret;
    }

Log in to reply
 

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