Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #Deterministic Finite Automata (DFA)
- '''
- 4 states of dfa:
- Q0: Initial State(space state)
- Q1: sign state
- Q2: digit state (digit formation takes place here)
- Q3: final halting state
- Transitions:
- Δ(q0, '\s') = q0 Δ(q1, '\d') = q2. Δ(q2, '\d') = q2
- Δ(q0, '[+-]') = q1 Δ(q1, '\D') = q3. Δ(q1, '\D') = q3
- Δ(q0, '\d') = q2
- Δ(q0, '[a-Z][A-Z]') = q3
- Reduction: states q1 and q2 can be merged (same transitions)
- '''
- class Solution:
- res, sgn = 0, 1
- def myAtoi(self, s: str) -> int:
- #transition functions
- def d1(ip):
- if ip.isspace():
- return 'q0'
- elif ip == '-':
- self.sgn = -1
- return 'q1'
- elif ip == '+':
- return 'q1'
- elif ip.isdigit():
- self.res = int(ip)
- return 'q1'
- else:
- return 'q2'
- def d2(ip):
- if ip.isdigit():
- self.res = (self.res<<3) + (self.res<<1) + int(ip)
- return 'q1'
- else:
- return 'q2'
- delta = {'q0': d1, 'q1': d2}
- curr = 'q0' #initial state
- for i in s:
- curr = delta[curr](i)
- if curr == 'q2': #final state
- break
- res = self.sgn*self.res
- res = max(res, -2**31)
- res = min(res, 2**31-1)
- return res
- #intuitive way
- class Solution:
- def myAtoi(self, s: str) -> int:
- sgn = 1
- i = 0
- n = len(s)
- while i<n and s[i].isspace():#can use lstrip()
- i += 1
- if i == n:
- return 0
- if s[i] == '+':
- i += 1
- sgn = 1
- elif s[i] == '-':
- i += 1
- sgn = -1
- lim1, lim2 = -pow(2, 31), pow(2, 31)-1
- res = 0
- while i<n and s[i].isdigit() and lim1<=res<=lim2:
- res = (res<<3) + (res<<1) +int(s[i])
- i += 1
- res = sgn*res
- if res < lim1:
- return lim1
- elif res > lim2:
- return lim2
- return res
Add Comment
Please, Sign In to add comment