今天說一下python如何實現(xiàn)羅馬數(shù)字轉(zhuǎn)整數(shù)报强,寫了三個方法
方法1:
#判斷當(dāng)前位置和下一個位置兩個字母是否在mydict中
class Solution:
???def romanToInt(self, s: str) -> int:
????????itemList = []
????????mydict = {'I':1,'V':5,'X':10,'L':50,'C':100,'D':500,'M':1000,'IV':4,'IX':9,'XL':40,'XC':90,'CD':400,'CM':900
????????i = 0
????????while i <len(s):
????????????if s[i] in 'IXC' and i!=len(s)-1:
????????????????if s[i:i+2] in mydict:
????????????????????itemList.append(mydict[s[i:i+2]])
????????????????????i += 2
????????????????else:
????????????????????itemList.append(mydict[s[i]])
????????????????????i += 1 ???
????????????else:
????????????????itemList.append(mydict[s[i]])
????????????????i += 1
????????return(sum(itemList))
運行時間56ms,消耗內(nèi)存14.9MB
方法2:
#把一個小值放在大值的左邊,就是做減法畅蹂,否則為加法
class Solution:
????def romanToInt(self, s: str) -> int:
????????mydict = {'I':1,'V':5,'X':10,'L':50,'C':100,'D':500,'M':1000}
????????return(sum([-mydict.get(item) if mydict.get(item)<mydict.get(s[i+1 if i+1 < len(s) else i]) else mydict.get(item) for i,item in enumerate(s)]))
運行時間76ms研侣,消耗內(nèi)存14.9MB
方法3:
#遍歷整個 ss 的時候判斷當(dāng)前位置和前一個位置的兩個字符組成的字符串是否在字典內(nèi)
class Solution:
????def romanToInt(self, s: str) -> int:
????????d = {'I':1, 'IV':3, 'V':5, 'IX':8, 'X':10, 'XL':30, 'L':50, 'XC':80, 'C':100, 'CD':300, 'D':500, 'CM':800, 'M':1000}
????????return sum(d.get(s[max(i-1, 0):i+1], d[n]) for i, n in enumerate(s))
運行時間60ms,消耗內(nèi)存14.8MB
也歡迎大家一起學(xué)習(xí)python哦http://www.daimaketang.com/register?inviteCode=XPGQQ