-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdemo126 字符串转换整数.py
40 lines (36 loc) · 1.12 KB
/
demo126 字符串转换整数.py
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
29
30
31
32
33
34
35
36
37
38
39
40
# 作者:宁方笑
# 开发时间:2021/7/30 21:17
INT_MAX=2**31-1
INT_MIN=-2**31
class Automaton: #自动机,dfa算法
def __init__(self):
self.state='start'
self.sign=1
self.ans=0
self.table = {
'start': ['start', 'signed', 'in_number', 'end'],
'signed': ['end', 'end', 'in_number', 'end'],
'in_number': ['end', 'end', 'in_number', 'end'],
'end': ['end', 'end', 'end', 'end'],
}
def get_col(self,c):
if c.isspace():
return 0
if c=='+' or c=='-':
return 1
if c.isdigit():
return 2
return 3
def get(self,c):
self.state=self.table[self.state][self.get_col(c)]
if self.state=='in_number':
self.ans=self.ans*10+int(c)
self.ans=min(self.ans,INT_MAX) if self.sign==1 else min(self.ans,-INT_MIN)
elif self.state=='signed':
self.sign=1 if c=='+' else -1
class Solution:
def myAtoi(self,str):
automaton=Automaton()
for c in str:
automaton.get(c)
return automaton.sign*automaton.ans