Skip to content

Commit a0aacda

Browse files
author
devin
committed
feat: 第十三题添加新思路
1 parent a215467 commit a0aacda

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

docs/Leetcode_Solutions/Python/0013._Roman_to_Integer.md

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -126,3 +126,35 @@ class Solution(object):
126126
'M':1000
127127
}.get(x)
128128
```
129+
130+
> 思路 2
131+
132+
除了 6 种特殊情况是双字母,其他都是单字母,并且任意一个数,特定特殊情况只会出现一次,因此先汇总特殊情况,再遍历叠加单字母即可
133+
134+
```python
135+
class Solution:
136+
def romanToInt(self, s: str) -> int:
137+
d = {
138+
'IV': 4,
139+
'IX': 9,
140+
'XL': 40,
141+
'XC': 90,
142+
'CD': 400,
143+
'CM': 900,
144+
'I': 1,
145+
'V': 5,
146+
'X': 10,
147+
'L': 50,
148+
'C': 100,
149+
'D': 500,
150+
'M': 1000
151+
}
152+
total = 0
153+
for v in ['IV', 'IX', 'XL', 'XC', 'CD', 'CM']:
154+
if v in s:
155+
total += d[v]
156+
s = s.replace(v, '')
157+
for v in s:
158+
total += d[v]
159+
return total
160+
```

0 commit comments

Comments
 (0)