문제 링크: https://leetcode.com/problems/roman-to-integer/description/
로만 숫자를 10진수 숫자로 치환하는 간단한 문제였다.
고려해야할 점은 보통 로만 숫자는 큰 숫자 -> 작은 숫자 순서로 쓰여지는데, 작은 숫자가 먼저온 후에 큰 숫자가 오면, 뒤에온 큰 숫자에 앞에 작은 숫자를 빼줘야한다는 점이었다.
class Solution:
def romanToInt(self, s: str) -> int:
# largest -> smallest
# exception: small -> large to substract
roman = {
"I": 1,
"V": 5,
"X": 10,
"L": 50,
"C": 100,
"D": 500,
"M": 1000
}
length = len(s)
result = 0
for i in range(length):
r = s[i]
if i < length - 1 and roman[r] < roman[s[i+1]]:
result -= roman[r]
else:
result += roman[r]
return result
시간 복잡도
n은 문자열의 길이
=> O(n)
'Algorithm > LeetCode' 카테고리의 다른 글
[LeetCode/Python] 125. Valid Palindrome (0) | 2025.04.01 |
---|---|
[LeetCode/Python] 58. Length of Last Word (0) | 2025.03.28 |
[LeetCode/Python] 9. Palindrome Number (1) | 2024.09.17 |
[LeetCode/Python] 67. Add Binary (1) | 2024.09.16 |
[LeetCode/Python] 1492. The kth Factor of n (1) | 2024.07.23 |