原题:https://leetcode.com/problems/roman-to-integer/
任务:将罗马数字转换为阿拉伯数字
思路:观察所有罗马数字字符,大多数符合加法规则,少数含4,9符合减法规则的有一个规律便是这种数左边的数字一定小于右边的数字,如IV,如果单独对应成独立字符,分别是1和5,而判断1小于,因此把这两个字符捆绑起来对应于4.具体代码如下:
class Solution(object):
def romanToInt(self,s):
"""
:type s: str
:rtype: int
"""
roman= ['M','CM','D','CD','C','XC','L','XL','X','IX','V','IV','I']
num= [1000,900,500,400,100,90,50,40,10,9,5,4,1]
dictionary= {
key: valuefor key, valuein zip(roman, num)
}
result= 0
if not s:
return result
i= 0
s += 'I'
while i< len(s)-1:
if dictionary[s[i]]>= dictionary[s[i+ 1]]:
result+= dictionary[s[i]]
i+= 1
else:
substring= s[i]+ s[i+1]
result+= dictionary[substring]
i+= 2
return result
结果:
Runtime:80 ms, faster than72.55%of Python online submissions for Roman to Integer.
Memory Usage:10.8 MB, less than41.00%of Python online submissions for Roman to Integer.
网友评论