原题
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
}
279

被折叠的 条评论
为什么被折叠?



