13. 罗马数字转整数 @Python @Go

原题

https://leetcode.cn/problems/roman-to-integer/description/

思路

字典

复杂度

时间:O(len(n))
空间:O(len(n))

Python代码

class Solution:
    def romanToInt(self, s: str) -> int:
        l1 = ['I', 'V', 'X', 'L', 'C', 'D', 'M', 'IV', 'IX', 'XL', 'XC', 'CD', 'CM']
        l2 = [1, 5, 10, 50, 100, 500, 1000, 4, 9, 40, 90, 400, 900]
        d = dict(zip(l1, l2))
        i = 0 
        ans = 0
        while i < len(s):
            if i+1 < len(s) and s[i:i+2] in d:
                ans += d[s[i:i+2]]
                i += 2 
            elif s[i] in d:
                ans += d[s[i]]
                i += 1 
        return ans 

Go代码

func romanToInt(s string) int {
	m := make(map[string]int)
	m["I"] = 1
	m["V"] = 5
	m["X"] = 10
	m["L"] = 50
	m["C"] = 100
	m["D"] = 500
	m["M"] = 1000
	m["IV"] = 4
	m["IX"] = 9
	m["XL"] = 40
	m["XC"] = 90
	m["CD"] = 400
	m["CM"] = 900
	i := 0
	var ans int
	for i < len(s) {
		if i+1 < len(s) {
			// 检查key是否在字典里
			sub := s[i : i+2]
			v, ok := m[sub]
			if ok {
				ans += v
				i += 2
			} else {
				ans += m[s[i:i+1]]
				i += 1
			}
		} else {
			ans += m[s[i:i+1]]
			i += 1
		}
	}
	return ans
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值