[leetcode] Roman to Integer

임택·2021년 2월 20일
0

알고리즘

목록 보기
34/63

problem

code

class Solution {
    public int romanToInt(String s) {
        Map<Character, Integer> map = new HashMap<>();
        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);
        
        char[] cArr = s.toCharArray();
        int sum = map.get(cArr[cArr.length - 1]);
        for (int i = cArr.length - 2; i >= 0; i--) {
            char c = cArr[i];
            int curr = map.get(c);

            // IXI, IIX, XIIIII invalid
            if (map.get(cArr[i + 1]) > curr) 
                sum -= curr;
            else 
                sum += curr;
        }
        return sum;
    }
}

Time: O(N),
Space: O(1), some language String is a char[]

profile
캬-!

0개의 댓글