Skip to content

Commit e93bc4c

Browse files
committed
LeetCode: 13 solved
1 parent 9e9a5a9 commit e93bc4c

File tree

1 file changed

+38
-1
lines changed

1 file changed

+38
-1
lines changed

Python/LeetCode/13. Roman to Integer.py

Lines changed: 38 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,44 @@
33
class Solution:
44

55
def romanToInt(self, s: str) -> int:
6+
# return self.solution1(s)
7+
# return self.solution2(s)
8+
return self.solution3(s)
9+
10+
def solution1(self, s):
11+
m = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
12+
13+
buf = 0
14+
res = 0
15+
16+
for i in range(len(s)):
17+
current = m[s[i]]
18+
isLast = i+1 == len(s)
19+
20+
if isLast or current >= m[s[i+1]]:
21+
res += current - buf
22+
buf = 0
23+
else:
24+
buf += current
25+
26+
return res
27+
28+
def solution2(self, s):
29+
m = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
30+
31+
prev = 0
32+
res = 0
33+
34+
for c in s:
35+
if m[c] <= prev:
36+
res += prev
37+
else:
38+
res -= prev
39+
prev = m[c]
40+
41+
return res + prev
42+
43+
def solution3(self, s):
644
if not s:
745
return 0
846

@@ -17,4 +55,3 @@ def romanToInt(self, s: str) -> int:
1755
res += roman[s[idx]]
1856

1957
return res
20-

0 commit comments

Comments
 (0)