[leetcode] Array/String (Easy) - 13. Roman to Integer

brandon·2025년 7월 9일

leetcode-array/strings

목록 보기
17/20

문제

Intuition

Recursion을 써서 각 If 조건에 맞는 값들을 계산하면 되겠다 생각했다.
또 I, X, 그리고 C에 관해서는 뒤에 나오는 글자가 각자 상황에 맞는 글자들이라면 -를 붙여 빼게 하면 되겠다고 생각했다.

Hashmap error:Line 3: error: expected hashMap.put('I', 1);

HashMap을 맏드는데 에러가 떴다.

In Java, statements like hashMap.put('I', 1); cannot exist directly at the top level of a class definition. They must be inside:
A method: The most common place for such operations.
An instance initializer block: Code that runs when an object of the class is created.
A static initializer block: Code that runs once when the class is loaded.
A constructor: To initialize the HashMap when an object is created.

Static 블록에 넣음으로서 해결했다.

답안

class Solution {
    private static HashMap<Character, Integer> hashMap = new HashMap<>();
    static {
        hashMap.put('I', 1);
        hashMap.put('V', 5);
        hashMap.put('X', 10);
        hashMap.put('L', 50);
        hashMap.put('C', 100);
        hashMap.put('D', 500);
        hashMap.put('M', 1000);
    }

    public int romanToInt(String s) {
        if (s.length() <= 0) {
            return 0;
        } else {
            if (s.charAt(0) != 'I' && s.charAt(0) != 'X' && s.charAt(0) != 'C') {
                int value = hashMap.get(s.charAt(0));
                return value + romanToInt(s.substring(1));
            } else {
                int value = hashMap.get(s.charAt(0));
                if (s.length() >= 2) {
                    if (s.charAt(0) == 'I') {
                        if (s.charAt(1) == 'V' || s.charAt(1) == 'X') {
                            return -1 * value + romanToInt(s.substring(1));
                        }
                    } else if (s.charAt(0) == 'X') {
                        if (s.charAt(1) == 'L' || s.charAt(1) == 'C') {
                            return -1 * value + romanToInt(s.substring(1));
                        }
                    } else if (s.charAt(0) == 'C') {
                        if (s.charAt(1) == 'D' || s.charAt(1) == 'M') {
                            return -1 * value + romanToInt(s.substring(1));
                        }
                    }
                }

                return value + romanToInt(s.substring(1));
            }
        }
    }
}

배울점

java에 대해서 더 배워야겠다는 생각을 했다.

profile
everything happens for a reason

0개의 댓글