DeepRest

String to Integer (atoi)

Jan 14th, 2022 (edited)
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.15 KB | None | 0 0
  1. #Deterministic Finite Automata (DFA)
  2. '''
  3. 4 states of dfa:
  4. Q0: Initial State(space state)
  5. Q1: sign state
  6. Q2: digit state (digit formation takes place here)
  7. Q3: final halting state
  8. Transitions:
  9. Δ(q0, '\s') = q0         Δ(q1, '\d') = q2.    Δ(q2, '\d') = q2
  10. Δ(q0, '[+-]') = q1       Δ(q1, '\D') = q3.    Δ(q1, '\D') = q3
  11. Δ(q0, '\d') = q2
  12. Δ(q0, '[a-Z][A-Z]') = q3
  13.  
  14. Reduction: states q1 and q2 can be merged (same transitions)
  15. '''
  16. class Solution:
  17.     res, sgn = 0, 1
  18.     def myAtoi(self, s: str) -> int:
  19.         #transition functions
  20.         def d1(ip):
  21.             if ip.isspace():
  22.                 return 'q0'  
  23.             elif ip == '-':
  24.                 self.sgn = -1
  25.                 return 'q1'
  26.             elif ip == '+':
  27.                 return 'q1'
  28.             elif ip.isdigit():
  29.                 self.res = int(ip)
  30.                 return 'q1'
  31.             else:
  32.                 return 'q2'
  33.         def d2(ip):
  34.             if ip.isdigit():
  35.                 self.res = (self.res<<3) + (self.res<<1) + int(ip)
  36.                 return 'q1'
  37.             else:
  38.                 return 'q2'
  39.    
  40.         delta = {'q0': d1, 'q1': d2}
  41.         curr = 'q0' #initial state
  42.         for i in s:
  43.             curr = delta[curr](i)
  44.             if curr == 'q2': #final state
  45.                 break
  46.         res = self.sgn*self.res
  47.         res = max(res, -2**31)
  48.         res = min(res, 2**31-1)
  49.         return res
  50.    
  51. #intuitive way
  52. class Solution:
  53.     def myAtoi(self, s: str) -> int:
  54.         sgn = 1
  55.         i = 0
  56.         n = len(s)
  57.         while i<n and s[i].isspace():#can use lstrip()
  58.             i += 1
  59.         if i == n:
  60.             return 0
  61.         if s[i] == '+':
  62.             i += 1
  63.             sgn = 1
  64.         elif s[i] == '-':
  65.             i += 1
  66.             sgn = -1
  67.         lim1, lim2 = -pow(2, 31), pow(2, 31)-1
  68.         res = 0
  69.         while i<n and s[i].isdigit() and lim1<=res<=lim2:
  70.             res = (res<<3) + (res<<1) +int(s[i])
  71.             i += 1
  72.         res = sgn*res
  73.         if res < lim1:
  74.             return lim1
  75.         elif res > lim2:
  76.             return lim2
  77.         return res
  78.    
  79.  
Add Comment
Please, Sign In to add comment