[LeetCode][python3]0013. Roman to Integer

Start the Journey
N2I -2020.03.18

1. My first Solution


  1. class Solution:
  2. def romanToInt(self, s: str) -> int:
  3. rom=["M","D","C","L","X","V","I"]
  4. digit=[1000,500,100,50,10,5,1]
  5. result=0
  6. if s.find("CM")>=0 or s.find("CD")>=0:
  7. result-=200
  8. if s.find("XC")>=0 or s.find("XL")>=0:
  9. result-=20
  10. if s.find("IX")>=0 or s.find("IV")>=0:
  11. result-=2
  12. for c in s:
  13. for r,d in zip(rom,digit):
  14. if c==r:
  15. result+=d
  16. return result
  17.  

Explanation:

Using find() function to solve the problem. When C+M=1000 and CM=900, this makes the result have a 200 gap. So we minus it first then count it as the same way. Same as CD,XC,XL,IX,IV.


2. Other solution


  1. class Solution:
  2. def romanToInt(self, s: str):
  3. symbol={'I':1,'V':5,'X':10, 'L':50, 'C':100, 'D':500, 'M':1000}
  4. output=[0]
  5. for i in s:
  6. if symbol[i]>output[-1]:
  7. output[-1]=symbol[i]-output[-1]
  8. else:
  9. output.append(symbol[i])
  10. return sum(output)
  11.  

Explanation:

The solution is using dict to save the pattern, and check out the special cases when smaller symbol is in front of a bigger symbol.