1. 读懂题目
注意: 提示中已明确,不会出现跨位的情况。所以是可以简化为左右数字的加减问题。
2. 分析,推导解法,产生思路。
解题思路:(1)字符转换为数字的问题。可使用列表list或字典dict,利用对应关系解题。
(2)对数字出现的问题,考虑左边小于右边则采用减法,左边大于右边则采用加法。
3. 代码实现
map_dic = {'I':1, 'V':5, 'X':10, 'L':50, 'C':100, 'D':500, 'M':1000}
class Solution(object):
def romanToInt(self, s):
"""
:type s: str
:rtype: int
"""
sum = 0
# 下标法/迭代器 遍历字符串
i = 1
print(len(s))
while(i < len(s)):
if (s[i-1] == 'I' and (s[i] == 'V'or s[i] == 'X')) or (s[i-1] == 'X' and (s[i] == 'L'or s[i] == 'C')) or (s[i-1] == 'C' and (s[i] == 'D'or s[i] == 'M')) :
sum += map_dic[s[i]] - map_dic[s[i-1]]
i = i+2
else:
sum += map_dic[s[i-1]]
i = i +1
if i < len(s)+1:
sum += map_dic[s[i-1]]
return sum
之前没有注意到,没有跨位的情况。下面为优化后的代码。
def romanToInt1(self, s): # 利用字典的下标,简化
sum = 0
for i in range(len(s)-1):
if map_dic[s[i]] < map_dic[s[i+1]]:
sum -= map_dic[s[i]]
print(map_dic[s[i]], map_dic[s[i + 1]], sum)
else:
sum += map_dic[s[i]]
sum += map_dic[s[-1]]
return sum