Java Solution using HashMap


  • 1
    C
    class Solution {
        
        public int romanToInt(String s) {
            
            HashMap<Character,Integer> romanMap = new HashMap<Character,Integer>();
            
            romanMap.put('I',1);
            romanMap.put('V',5);
            romanMap.put('X',10);
            romanMap.put('L',50);
            romanMap.put('C',100);
            romanMap.put('D',500);
            romanMap.put('M',1000);
            
            char[] input = s.toCharArray();
            int sum = 0;
            
            for(int i=0; i<input.length; i++){
                
                int left = romanMap.get(input[i]);
                int right = 0;
                
                if ((i+1) < input.length){
                    right = romanMap.get(input[i+1]);
                }
    
                if(left >= right){
                    sum = sum + left;
                }else{
                    sum = sum - left;
                }
            }
            
            return sum;
            
        }
    }
    

    First, we associate each roman character with a number.
    Then, we loop through the roman character array.
    If the left-hand side is greater or equal to the right-hand side, then we can add the left-hand side character's corresponding number to the sum.
    If the left-hand side is strictly smaller than the right-hand side, then we subtract the left-hand side character's corresponding number from the sum.


  • 0
    L

    @chunyinjohnnychan said in Java Solution using HashMap:

    class Solution {

    public int romanToInt(String s) {
        
        HashMap<Character,Integer> romanMap = new HashMap<Character,Integer>();
        
        romanMap.put('I',1);
        romanMap.put('V',5);
        romanMap.put('X',10);
        romanMap.put('L',50);
        romanMap.put('C',100);
        romanMap.put('D',500);
        romanMap.put('M',1000);
        
        char[] input = s.toCharArray();
        int sum = 0;
        
        for(int i=0; i<input.length; i++){
            
            int left = romanMap.get(input[i]);
            int right = 0;
            
            if ((i+1) < input.length){
                right = romanMap.get(input[i+1]);
            }
    
            if(left >= right){
                sum = sum + left;
            }else{
                sum = sum - left;
            }
        }
        
        return sum;
    

    Brilliant,
    Thanks for sharing.


Log in to reply
 

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