Permutations

Roman to Integer

Great Version

1
2
3
4
5
6
7
8
9
10
11
class Solution(object):
def romanToInt(self, s):
"""
:type s: str
:rtype: int
"""
res, p = 0, 'I'
DICT = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
for x in s[::-1]:
res, p = res - DICT[x] if DICT[x] < DICT[p] else res + DICT[x], x
return res

Ugly Version

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class Solution(object):
def romanToInt(self, s):
"""
:type s: str
:rtype: int
"""
res = []
LEFT = {'IV': 4, 'IX': 9, 'XL': 40, 'XC': 90, 'CD': 400, 'CM': 900}
DICT = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
list_s = list(s)
len_s = len(s)
i = 0
while True:
if i == len_s - 1:
res.append(DICT[list_s[i]])
break
elif i + 1 < len_s:
left = list_s[i] + list_s[i + 1]
if left in LEFT:
res.append(LEFT[left])
i += 2
else:
res.append(DICT[list_s[i]])
i += 1
else:
break
# print res
return sum(res)

output

1
2
In [476]: s = Solution(); print s.romanToInt('MCDLXXVI')
1476

leet code