13. Roman to Integer

JJ·2020년 11월 26일
0

Algorithms

목록 보기
2/114
	public int romanToInt(String s) {
        Map<Character, Integer> map = new HashMap<Character, Integer>();
        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 i = 0;
        int sum = 0; 
        int temp = 0;
        while (i < s.length() - 1) {
            if (map.get(s.charAt(i)) > map.get(s.charAt(i+1))) {
                sum += map.get(s.charAt(i));
            } else if (map.get(s.charAt(i)) < map.get(s.charAt(i+1))) {
                temp += map.get(s.charAt(i));
                sum -= temp;
                temp = 0; 
            } else {
                temp += map.get(s.charAt(i));
            }
            i++; 
        }
        
        sum += map.get(s.charAt(i));
        sum += temp; 
        return sum;
        
    }

Did not run b/c:

  • Didn't realize that the subtractions only happen once.

Knowing this fact, new solution:

	public int romanToInt(String s) {
        //int I = 1, V = 5, X = 10, L = 50, C = 100, D = 500, M = 1000;
        Map<Character, Integer> map = new HashMap<Character, Integer>();
        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 i = 0;
        int sum = 0; 
        while (i < s.length() - 1) {
            if (map.get(s.charAt(i)) >= map.get(s.charAt(i+1))) {
                sum += map.get(s.charAt(i));
            } else {
                sum -= map.get(s.charAt(i));
            }
            i++; 
        }
        
        sum += map.get(s.charAt(i));
        return sum;   
    }

Runtime: 8 ms, faster than 14.17% of Java online submissions for Roman to Integer.
Memory Usage: 43 MB, less than 5.11% of Java online submissions for Roman to Integer.

Important Points

  • The numerals only get subtracted once
  • If the number after is greater than number before, subtract the number before from the sum.
  • Otherwise, add and keep moving on
  • Make sure to add the last value after the for loop - that value will always be added.

How can I make it faster?

  • Skip numbers by 2
  • 이부분은 이해가 안가서 풍씨와 함께 보고싶네요^^

0개의 댓글