DFA有穷向量机,可以简单用于层层嵌套判断较为复杂的场景中,主要是梳理清楚状态,及在各个状态下会得到一个什么样的值。
#include <iostream>
#include <string>
#include <unordered_map>
#include <vector>
#include <algorithm>
using namespace std;
class Automaton
{
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" }}
};
int Get_col(char c)
{
if (isspace(c)) return 0;
if (c == '+' || c == '-') return 1;
if (isdigit(c)) return 2;
return 3;
}
public:
int sign = 1;
long long ans = 0;
void Get(char c)
{
state = table[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 str)
{
Automaton antomaton;
for (char c : str)
{
antomaton.Get(c);
}
return antomaton.ans * antomaton.sign;
}
};
int main()
{
string str = " 12345";
Solution s;
cout << s.myAtoi(str) << endl;
return 0;
}