代码实现
粗糙的实现
class Solution:def romanToInt(self, s: str) -> int:res=0length=len(s)dic={}dic['I']=1dic['V']=5dic['X']=10dic['L']=50dic['C']=100dic['D']=500dic['M']=1000res=0i=0while i<length:if i<length-1:if s[i]=='I' and s[i+1]=='V':res=res+dic['V']-1i=i+2elif s[i]=='I' and s[i+1]=='X':res=res+dic['X']-1i=i+2elif s[i]=='X' and s[i+1]=='L':res=res+dic['L']-10i=i+2elif s[i]=='X' and s[i+1]=='C':res=res+dic['C']-10i=i+2elif s[i]=='C' and s[i+1]=='D':res=res+dic['D']-100i=i+2elif s[i]=='C' and s[i+1]=='M':res=res+dic['M']-100i=i+2else:res=res+dic[s[i]]i=i+1else:res=res+dic[s[i]]i=i+1return res
解法
从题干中得知:
I可以放在V(5) 和X(10) 的左边,来表示 4 和 9。X可以放在L(50) 和C(100) 的左边,来表示 40 和 90。C可以放在D(500) 和M(1000) 的左边,来表示 400 和 900。
只有这六种情况下,才使用减法,在其他情况下罗马数字先大后小组合->开始的六种情况先小后大。【总结出共性】
所以我们处理一个字符时,若它比后面的字符小,则应用减法,否则正常累加。
class Solution:def romanToInt(self, s: str) -> int:length=len(s)res=0dic={"I":1,"V":5,"X":10,"L":50,"C":100,"D":500,"M":1000}for i in range(length-1):if dic[s[i]]<dic[s[i+1]]:res=res-dic[s[i]]else:res=res+dic[s[i]]res=res+dic[s[-1]]return res
13、python实现罗马数字转整数
[LeetCode] 13. Roman to Integer 罗马数字转化成整数 # 强烈推荐
