• [leetcode] Roman to Integer @ Python


    题目: https://oj.leetcode.com/problems/roman-to-integer/

    Given a roman numeral, convert it to an integer.

    Input is guaranteed to be within the range from 1 to 3999.

    思路: 见代码注解

    代码:

    class Solution:
        # @return an integer
        def romanToInt(self, s):
            #从前往后扫描,用一个临时变量记录分段数字。
            #如果当前比前一个大,说明这一段的值应该是当前这个值减去上一个值。比如IV = 5 – 1;
            #否则,将当前值加入到结果中,然后开始下一段记录。比如VI = 5 + 1, II=1+1
            # 时间复杂度O(n),空间复杂度O(1)
            dict = {'M':1000, 'D':500, 'C':100, 'L':50, 'X':10, 'V':5, 'I':1}
            res = 0
            for i in range(len(s)):
                if i > 0 and dict[s[i]] >  dict[s[i - 1]]:
                    res += dict[s[i]] - 2* dict[s[i - 1]]
                else:
                    res += dict[s[i]]
            return res
  • 相关阅读:
    dart 函数迭代器
    dart 编译
    dart 扩展方法
    dart 包
    默认2345导航
    (24)WPF 数据绑定
    (22)WPF 控件模板
    JSP慕课网之Session
    HTML <td> 标签的 colspan 属性
    HTML Input属性
  • 原文地址:https://www.cnblogs.com/asrman/p/3976325.html
Copyright © 2020-2023  润新知