【leetcode】13. 罗马数字转整数

发布于:2025-08-17 ⋅ 阅读:(14) ⋅ 点赞:(0)

题目

13. 罗马数字转整数

在这里插入图片描述

题解

1. 枚举,双指针

class Solution(object):
    def romanToInt(self, s):
        """
        :type s: str
        :rtype: int
        """
        # 双指针
        s_list = list(s)
        slow = 0 
        fast = 1
        n = len(s)
        rom_map = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
        res = 0
        if n == 1:
            return rom_map[s_list[0]]

        while fast < n:
            if s_list[slow] in ['I'] and s_list[fast] in ['V', 'X']:
                res += rom_map[s_list[fast]] - rom_map[s_list[slow]]
                slow += 2
                fast += 2
                if slow < n and fast >= n:
                    res += rom_map[s_list[slow]]
            elif s_list[slow] in ['X'] and s_list[fast] in ['L', 'C']:
                res += rom_map[s_list[fast]] - rom_map[s_list[slow]]
                slow += 2
                fast += 2
                if slow < n and fast >= n:
                    res += rom_map[s_list[slow]]
            elif s_list[slow] in ['C'] and s_list[fast] in ['D', 'M']:
                res += rom_map[s_list[fast]] - rom_map[s_list[slow]]
                slow += 2
                fast += 2
                if slow < n and fast >= n:
                    res += rom_map[s_list[slow]]
            else:
                res += rom_map[s_list[slow]]
                slow += 1
                fast += 1
                if fast >= n:
                    res += rom_map[s_list[slow]]
        return res



2. 前面小于后面则减

class Solution(object):
    def romanToInt(self, s):
        """
        :type s: str
        :rtype: int
        """
        rom_map = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
        res = 0
        n = len(s)

        for i, ch in enumerate(s):
            value = rom_map[ch]
            if i < n - 1 and value < rom_map[s[i + 1]]:
                res -= value
            else:
                res += value


        return res




网站公告

今日签到

点亮在社区的每一天
去签到