题目
题目简化分析
字符串转换问题。满足以下要求:
- 第一个非空字符可以是数字或者符号
-,+
- 从第二个非空字符开始,在遇到非数字字符时结束。
- 若无法满足上述要求,返回0
Insight
实现
相比正则表达式的方法,自动机的方法似乎可以适配更复杂的规则情况,所以重写了官方自动机的方法。
// 重写:21.93% / 9.09% | 官方:6.64% / 9.09% | 区别在于官方答案在查询到`end`后会继续执行程序
// 重写的答案在查询到`end`后会跳出查询程序,直接进入返回结果的部分。
class Automatic(object):
def __init__(self):
self.status = 'starter'
self.signed = 1
self.nums = 0
self.table = {
'starter':['starter','signed','nums','end'],
'signed':['end','end','nums','end'],
'nums':['end','end','nums','end'],
}
def get_c_col(self,c):
if c.isspace():
return 0
elif c == '-' or c == '+':
return 1
elif c.isdigit():
return 2
else:
return 3
def get_nums(self):
return self.signed * self.nums
def get_c(self,c):
self.status = self.table[self.status][self.get_c_col(c)]
if self.status == 'end':
return 1
elif self.status == 'signed':
self.signed = -1 if c == '-' else 1
elif self.status == 'nums':
self.nums = 10*self.nums + int(c)
else:
pass
class Solution(object):
def myAtoi(self, str):
"""
:type str: str
:rtype: int
"""
MIN = -2 ** 31
MAX = 2 ** 31-1
auto = Automatic()
for c in str:
if auto.get_c(c):
break
sum = min(max(auto.get_nums(),MIN),MAX)
return sum