Problem Solving

[leetcode - Python] Roman to Integer

Dev_en 2022. 7. 19. 14:29

문제 설명

https://leetcode.com/problems/roman-to-integer/submissions/

 

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

  • 난이도 - Medium

 

문자열로 주어지는 로마 숫자를 아라비아 숫자로 바꾸는 문제


접근 방법

기본적으로 알파벳을 만나면 해당 숫자를 더해주는데,

만난 알파벳보다 그 다음 알파벳이 더 크면 빼준다.

 

이때 주의해야할 점은, 문제 예시엔 I, X, C에 대한 총 6가지 예시만 나와있지만,

모든 알파벳에 대해 만난 알파벳보다 그 다음 알파벳이 더 크면 빼줘야 하는 규칙이 적용된다.


답안 코드 1. 조건문

Runtime: 112 ms (7.42%)
Memory Usage: 13.9 MB (76.17%)
class Solution:
    def romanToInt(self, s: str) -> int:
        result = 0
        for i in range(len(s)):
            if s[i] == 'I':
                if i <= len(s) - 2 and (s[i+1] in ['V', 'X']) :
                    result -= 1
                else:
                    result += 1
                    
            elif s[i] == 'V':
                result += 5
            
            elif s[i] == 'X':
                if i <= len(s) - 2 and (s[i+1] in ['L', 'C']):
                    result -= 10
                else:
                    result += 10         
            elif s[i] == 'L':
                result += 50
            elif s[i] == 'C':
                if i <= len(s) - 2 and (s[i+1] in ['D', 'M']):
                    result -= 100
                else:
                    result += 100
            elif s[i] == 'D':
                result += 500
            elif s[i] == 'M':
                result += 1000
        
        return result

 

답안 코드 2.  딕셔너리

Runtime: 53 ms (87.62%)
Memory Usage: 13.9 MB (76.17%)
class Solution:
    def romanToInt(self, s: str) -> int:
        mapping = {
            'I': 1,
            'V': 5,
            'X': 10,
            'L': 50,
            'C': 100,
            'D': 500,
            'M': 1000
        }
        result = 0
        for i in range(len(s)-1):
            if mapping[s[i]] < mapping[s[i+1]]:
                result -= mapping[s[i]]
            else:
                result += mapping[s[i]]
        result += mapping[s[len(s)-1]]
        return result