1、自己解法,一次遍历,找出符合条件的数字,转化
class Solution:
def myAtoi(self, s: str) -> int:
# 定义一个数组存数字?
up = pow(2,31)-1
low = -up-1
slen = len(s)
i,start,renum,sign = 0,-1,0,1
restr = []
if slen<1:
return 0
# 找到起始位置
for c in s:
if(c != ' '):
if(c == '-'):
sign = -1
start = i+1
break
elif(c == '+'):
sign = 1
start = i+1
break
elif(c>='0' and c<='9'):
sign = 1
start = i
break
else:
return 0
i=i+1
# 存入数组
i=start
while(i<slen):
if(s[i]<'0' or s[i]>'9'):
break
else:
restr.append(s[i])
i = i+1
# 转化成数字
for c in (restr):
renum = renum*10 + int(c)-int('0')
if(sign*renum > up):
return up
elif(sign*renum < low):
return low
else:
return sign*renum
2、正则(现学一下)
class Solution:
def myAtoi(self, s: str) -> int:
UP = 2147483647
LOW = -2147483648
s = s.lstrip() # 清除前面的空格
temp = re.compile('^[\+\-]?\d+') # \+\- 或+或- ? 可有可无 \d 数字 +前面一个或多个 ^ 从头开始匹配
num = temp.findall(s) # findall函数,找出匹配字符串
num = int(*num) # 解包
if(num>UP):
return UP
elif(num<LOW):
return LOW
else:
return num
简单学习正则,学习lstrip函数,findall函数 和 解包
3、有限状态机(重点)
官方解答的图:
UP = 2147483647
LOW = -2147483648
class Automata:
def __init__(self):
self.state="start"
self.ans=0
self.sign=1
# 如果前面是start/sign/innum/end状态
# 后面出现各种字符所对应的状态应该是...
self.table={
"start":["start","sign","innum","end"],
"sign":["end","end","innum","end"],
"innum":["end","end","innum","end"],
"end":["end","end","end","end"]
}
def get_s(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_s(c)]
if self.state=="innum":
self.ans = self.ans*10+int(c)
if self.ans*self.sign > UP:
self.ans=UP
if self.ans*self.sign < LOW:
self.ans=self.sign*LOW
if self.state=="sign" and c=='-':
self.sign=-1
class Solution:
def myAtoi(self, s: str) -> int:
auto=Automata()
for c in s:
auto.get(c)
if auto.state=="end":
break
return auto.ans*auto.sign