My accepted Java solution(313ms)


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

Log in to reply
 

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