leetcode第八题,字符串向数字的转换一题,答案用到了有限状态自动机的方法,具体写了一个类
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 == '+' or 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 automaton;
for (char c : str)
automaton.get(c);
return automaton.sign * automaton.ans;
}
};
定义了四个状态,start时开始,在start状态如果接受到空格字符还是start,接受到正负号就变成signed状态,如果在signed状态下,接受到的字符不是数字字符,一律转到end状态(为题目所定义的规则)。
定义了函数get,根据读到的字符改变状态机的状态state,table用unordered_map来定义,key是string类型,value相当于是字符串数组,table用来确定state,table的值是当前状态state,键是根据下一个字符而将改变成的状态。
最终在Solution类中只需要初始化该类,并且读入字符,改变状态机内部状态,返回类成员sign和ans乘积即可