题目描述
解法
除去空格只能是数字形式这一点不知道如何判断。
力扣上的优秀解法
#include <iostream>
#include <string>
using namespace std;
class Solution {
public:
int myAtoi(string str) {
// 字符串长度
unsigned long len = str.length();
// 去除前导空格 获取到起始地址
int index = 0;
while (index < len) {
if (str[index] != ' ') {
break;
}
index++;
}
if (index == len) {
return 0;
}
int sign = 1;// 标记正负
// 处理第 1 个非空字符为正负符号,这两个判断需要写在一起
if (str[index] == '+') {
index++; // 继续往后读取字符
} else if (str[index] == '-') {
sign = -1;
index++;
}
// 根据题目限制,只能使用 int 类型
int res = 0;
while (index < len) {
char curChar = str[index];
if (curChar < '0' || curChar > '9') {
break;
}
// 只要不是数字直接返回0
// 判断是否超出int的表示范围
if (res > INT_MAX / 10 || (res == INT_MAX / 10 && (curChar - '0') > INT_MAX % 10)) {
return INT_MAX;
}
if (res < INT_MIN / 10 || (res == INT_MIN / 10 && (curChar - '0') > -(INT_MIN % 10))) {
return INT_MIN;
}
// 不用等到最后再处理,第一项是负数之后直接加倍就可以
res = res * 10 + sign * (curChar - '0');
index++;
}
return res;
}
};
力扣上面的自动机解法
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;
}
};