classAutomaton{
string state ="start";
unordered_map<string, vector<string>> 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"}}};intget_col(char c){if(isspace(c))return0;if(c =='+'or c =='-')return1;if(isdigit(c))return2;return3;}public:int sign =1;longlong ans =0;voidget(char c){
state = table[state][get_col(c)];if(state =="in_number"){
ans = ans *10+ c -'0';
ans = sign ==1?min(ans,(longlong)INT_MAX):min(ans,-(longlong)INT_MIN);}elseif(state =="signed")
sign = c =='+'?1:-1;}};classSolution{public:intmyAtoi(string str){
Automaton automaton;for(char c : str)
automaton.get(c);return automaton.sign * automaton.ans;}};
作者:LeetCode-Solution
链接:https://leetcode-cn.com/problems/string-to-integer-atoi/solution/zi-fu-chuan-zhuan-huan-zheng-shu-atoi-by-leetcode-/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。