上面是官方自动机图解模型
' ' | +/- | number | other | |
---|---|---|---|---|
start | start | signed | in_number | end |
signed | end | end | in_number | end |
in_number | end | end | in_number | end |
end | end | end | end | end |
#官方python代码
#
# @lc app=leetcode.cn id=8 lang=python3
#
# [8] 字符串转换整数 (atoi)
#
# @lc code=start
INT_MAX = 2**31-1
INT_MIN = -2**31
class Automaton:
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, s: str) -> int:
automaton = Automaton()
for c in s:
automaton.get(c)
return automaton.sign*automaton.ans
# @lc code=end
//官方C++代码
class Automation{
string state="start";
unordered_map<string,vector<string>> tabel={
{"start",{"start","signed","in_number","end"}},
{"signed",{"end","end","in_number","end"}},
{"in_number",{"end","end","in_number","end"}},
{"end",{"end","end","end","end"}}
};
int get_col(char c){
if(isspace(c)) return 0;
if(c=='+' or c=='-') return 1;
if(isdigit(c)) return 2;
return 3;
}
public:
int sign=1;
long long ans=0;
void get(char c){
state=tabel[state][get_col(c)];
if (state=="in_number"){
ans=ans*10+c-'0';
ans=sign==1?min(ans,(long long)INT_MAX):min(ans,-(long long)INT_MIN);
}
else if(state=="signed")
sign=c=='+'?1:-1;
}
};
class Solution {
public:
int myAtoi(string s) {
Automation automation;
for (char c:s)
automation.get(c);
return automation.sign * automation.ans;
}
};