Inline Java Solution


  • 0
    J

    class Solution {
    public int romanToInt(String s) {

        if(s == null || s.length() < 1) {
            return -1;
        }
        
        Map<Character, Integer> hm = initRomanHash();
        int newInt = 0, curCount = 1;
        char cur = s.charAt(0);
      
        for(int i = 1; i < s.length(); i++) {
            char letter = s.charAt(i);
       
            if(letter == cur) {
                curCount++;
            } else {
                if(hm.get(letter) > hm.get(cur)) {
                    newInt -= curCount*hm.get(cur);
                } else {
                    newInt +=curCount*hm.get(cur);
                }
                curCount = 1;
                cur = letter;
            }
        }    
        return newInt + curCount*hm.get(cur);
    }
    
    private Map<Character, Integer> initRomanHash {
        Map<Character, Integer> hm = new HashMap<Character, Integer>();
        hm.put('I', 1);
        hm.put('V', 5);
        hm.put('X', 10);
        hm.put('L', 50);
        hm.put('C', 100);
        hm.put('D', 500);
        hm.put('M', 1000);
        return hm;
    }
    

    }


Log in to reply
 

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