My HashMap Java Solution


  • 0
    T
    public int romanToInt(String s) {
        HashMap<Character, Integer> m = new HashMap();
        m.put('I', 1);
        m.put('V', 5);
        m.put('X', 10);
        m.put('L', 50);
        m.put('C', 100);
        m.put('D', 500);
        m.put('M', 1000);
      
        int sum = 0;
        int counter = 1;
        int prev = 0;
        
        for (char c : s.toCharArray()) {
            
            int val = m.get(c);
            sum += val;
            if (val == prev) {
                counter++;
            } else {
                counter = 1;
            }
            if (val> prev && prev != 0) {
                sum-= (++counter)*prev;
                counter = 1;
            }
            prev = val;
    
        }
        return sum;
    }

  • 0
    T

    After completing on my own I saw the switch case and simpler solutions. Those are definitely more clever approaches, but I like to think mine uses a good data structure for this. O(n) time and space?


Log in to reply
 

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