Roman to Integer语言 - Python



我目前已经使用以下代码来解决以下问题:

https://leetcode.com/problems/roman-to-integer/

def romanToInt(s: str) -> int:
dict = {'I': 1, 'V': 5, 'X': 10,'L': 50,'C': 100, 'C': 100,'D': 500,'M': 1000}
s = list(s)
x = 0
y = 1
max_count = len(s) - 1
value = 0
print(s)
#Iterate through the numbers one by one with two pointers x and y. 
#If x is bigger than y move both 1 point forward.
#If x is less than y move both 2 points forward.
while y <= max_count:
if dict[s[x]] > dict[s[y]]:
value =  value + dict[s[x]]
x += 1
y += 1
elif dict[s[x]] < dict[s[y]]:
value =  value + (dict[s[y]] - dict[s[x]])
x += 2
y += 2
else:
value = value + dict[s[x]] + dict[s[y]]
x += 1
y += 1
return value
print(romanToInt(s = 'III'))

所以目前我面临的问题是在迭代过程中计算一个额外的值。我知道问题出在指针x的移动和计算上,但我似乎无法弄清楚。

任何帮助都会有所帮助。

展开我的评论。对于您的else,不要添加s[y]的值,因为s[y]将是您的下一个s[x],您将加倍计算。

此外,您还需要检查何时到达字符串的末尾,以确保在适当的时候捕获最后一个值。

考虑:

def romanToInt(s: str) -> int:
dict = {'I': 1, 'V': 5, 'X': 10,'L': 50,'C': 100, 'C': 100,'D': 500,'M': 1000}
s = list(s)
x = 0
y = 1
max_count = len(s) - 1
value = 0

#Iterate through the numbers one by one with two pointers x and y. 
#If x is bigger than y move both 1 point forward.
#If x is less than y move both 2 points forward.
while x <= max_count:
if y == len(s): 
value = value + dict[s[x]]
break
elif dict[s[x]] > dict[s[y]]:
value =  value + dict[s[x]]
x += 1
y += 1
elif dict[s[x]] < dict[s[y]]:
value =  value + (dict[s[y]] - dict[s[x]])
x += 2
y += 2
else:
value = value + dict[s[x]] 
x += 1
y += 1
return value

print(romanToInt(s = 'III'))
print(romanToInt(s = 'IV'))
print(romanToInt(s = 'VI'))
print(romanToInt(s = 'V'))

3
4
6
5

这应该有效:

def romanToInt(s: str) -> int:
dict = {'I': 1, 'V': 5, 'X': 10,'L': 50,'C': 100,'D': 500,'M': 1000}
total_value = 0
last_value = None
for letter in s[::-1]:
current_value = dict[letter]
if last_value is None or last_value <= current_value:
total_value += current_value
else:
total_value -= current_value
last_value = current_value

return total_value

最好只使用for循环,并将当前值加总或减去。。。例如IX=40。当你在I时,你会发现X更大,所以你可以减去10,然后在得到X时加50。-10+50->40

在您的情况下,您可以将其更改为:

def romanToInt(s: str) -> int:
dict = {'I': 1, 'V': 5, 'X': 10,'L': 50,'C': 100, 'C': 100,'D': 500,'M': 1000}
s = list(s)
x = 0
y = 1
max_count = len(s) - 1
value = 0

while y <= max_count:
if dict[s[x]] > dict[s[y]]:
value += dict[s[x]]
x += 1
y += 1
elif dict[s[x]] < dict[s[y]]:
value -= dict[s[x]]
x += 1
y += 1
else:
value += dict[s[x]] 
x += 1
y += 1
value += dict[s[x]] 
return value

所以你只需要x+=1一次,你可以把它简化为

def romanToInt(s: str) -> int:
dict = {'I': 1, 'V': 5, 'X': 10,'L': 50,'C': 100, 'C': 100,'D': 500,'M': 1000}
s = list(s)
x = 0
y = 1
max_count = len(s) - 1
value = 0
while y <= max_count:
if dict[s[x]] < dict[s[y]]:
value -= dict[s[x]]
else:
value += dict[s[x]] 
x += 1
y += 1
value += dict[s[x]] 
return value

请记住,这不会包括最后一个字符(索引限制(,所以你必须单独添加

最新更新