Algorithm/LeetCode

LeetCode 13. Roman to Integer

hhsaebom 2021. 1. 7. 18:35

문제링크: leetcode.com/problems/roman-to-integer/

 

Roman to Integer - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

문제 요약: 문자열(로마숫자)이 주어졌을때, 숫자로 변경하시오.

 

문제 접근: 로마숫자에 대응되는 숫자를 맵에다 담고, 단순하게 if, else를 여러개 두어서 해결했다. 주의할점은 만약 빼야하는 숫자 (예: IV 5 - 1) 일 경우에는 반복문 변수(i)를 한번 더 더해서 다음 루프에서 다음다음 char를 보게 해야한다.

 

구현 코드: 

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

 

싫어요가 많아서 안풀라했지만, easy 문제 정복하기 위해서 풀어봤다.