[LeetCode][Java] Roman To Integer

최지수·2021년 10월 5일
0

Algorithm

목록 보기
18/77
post-thumbnail

지난번에 푼, Integer To Roman의 반대 문제입니다! 그래서 이번엔 이전 로직을 응용해봤어요.

문제

Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M.

SymbolValue
I1
V5
X10
L50
C100
D500
M1000

For example, 2 is written as II in Roman numeral, just two one's added together. 12 is written as XII, which is simply X + II. The number 27 is written as XXVII, which is XX + V + II.

Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used:

  • I can be placed before V (5) and X (10) to make 4 and 9.
  • X can be placed before L (50) and C (100) to make 40 and 90.
  • C can be placed before D (500) and M (1000) to make 400 and 900.

Given an roman numeral, convert it to a integer.

제한사항

  • 1 \leq s.length \leq 15
  • s contains only the characters ('I', 'V', 'X', 'L', 'C', 'D', 'M').
    It is guaranteed that s is a valid roman numeral in the range [1, 3999]

접근

Roman 숫자로 구성된 문자열이 주어지면 이를 정수로 반환하는 문제입니다.

이와 반대되는 문제인 Integer To Roman에선 각 수치1000, 900, 500, 400...들을 배열에 따로 저장해서 주어진 매개변수 값을 빼가는 방식으로 했었어요.

그래서 이번엔 반대로 매개변수로 주어진 문자열의 RomanM, CM, D, CD,...을 빼가면서 답을 도출하는 방식으로 접근했고, 아주 빠른 방법은 아니었지만 정답을 제출했어요.

이번엔 최적화보다는 이전에 경험한 접근 방식에 익숙해지고, StringBuilder를 활용하는 것에 중점을 두었어요.

class Solution {
    public int romanToInt(String s) {
        String[] romans = { "M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I" };
        int[] integers = { 1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1 };

        int answer = 0;

        StringBuilder sb = new StringBuilder(s);
        for(int i = 0; i < romans.length; ++i){
            String roman = romans[i];
            int integer = integers[i];
            // 문자열이 현재 확인하는 Roman 길이보다 같거나 많아야 합니다.
            while(sb.length() >= roman.length() && sb.substring(0, roman.length()).equals(roman)){
                answer += integer;
                sb.delete(0, roman.length());
            }
        }

        return answer;
    }
}
profile
#행복 #도전 #지속성

0개의 댓글