标签:style blog http color io ar for div sp
题目: 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
[leetcode] Roman to Integer @ Python
标签:style blog http color io ar for div sp
原文地址:http://www.cnblogs.com/asrman/p/3976325.html