题目
8-字符串转换整数 (atoi)
https://leetcode-cn.com/problems/string-to-integer-atoi/
题解
优秀题解
https://leetcode-cn.com/problems/string-to-integer-atoi/solution/zi-fu-chuan-zhuan-huan-zheng-shu-atoi-by-leetcode-/
- 梳理好一共有几种状态(signed状态也要能够想到)
- 梳理好有几种符号(能把重要的摘出来,把其他的归为other)
实现展示我的第一版臃肿且不对的代码:
基本是边提交边试错边修改,结果还不对哈哈哈哈
class Solution {
public:
int myAtoi(string s) {
// ascii num -> capital -> lower case
if (s.empty() &&
(s[0] >= 'a' && s[0] <= 'z' ||
s[0] >= 'A' && s[0] <= 'Z' ||
s[0] == '.') ||
((s.size() > 1) &&
(s[0] == '-' ||
s[0] == '+') &&
(s[1] < '0' ||
s[1] > '9'))) {
return 0;
}
int result = 0;
int sign = 1;
for (auto c: s) {
if ((c >= 'a' && c <= 'z') || c == '.') {
// result = 0;
// sign = 1;
break;
}
if (c == ' ') {
// result = 0;
// sign = 1;
continue;
}
if (c == '-') {
sign = -1;
result = 0;
continue;
} else if (c == '+') {
sign = 1;
result = 0;
continue;
}
int tmp = c - '0';
if ((result > 214748364) ||
(result == 214748364 && sign < 0 && tmp > 8) ||
(result == 214748364 && sign > 0 && tmp > 7)) {
if (sign > 0) {
return 2147483647;
} else {
return -2147483648;
}
}
result = result * 10 + tmp;
}
if (sign > 0) {
return result;
} else {
return sign * result;
}
}
};
自己手写了一遍:
最佳路径是:
看一遍题目,确定思路
自己实现一下,踩个坑(如果有时间)
看一下和题解的思路是否相似,确认自己没有跑偏
要保证理解思路的情况下再动手,否则对着代码敲是没有意义!
复现的时候要自己写,必须思考了再看答案,这样就知道可能的考点在哪里
class Automation {
private:
string state = "start";
// path: " ", "+/-", "num", "other"
// 不同的路径会从一个state 转移到另一个 state
unordered_map<string, vector<string>> automation_table = {
{"start", {"start", "signed", "number", "end"}},
{"signed", {"end", "end", "number", "end"}},
{"number", {"end", "end", "number", "end"}},
{"end", {"end", "end", "end", "end"}}
};
int get_path(char c) {
if (c == ' ') return 0;
if (c == '+' || c == '-') return 1;
if (c >= '0' && c <='9') return 2;
return 3;
}
public:
int sign = 1;
long long result = 0;
void get_single_char(char c) {
// state 要用索引从 table 中取出
state = automation_table[state][get_path(c)];
// 在特定的状态下进行特定的操作
if (state == "signed" && c == '-') {
sign = -1;
} else if (state == "number") {
int tmp = c - '0';
if ((sign < 0) &&
((result > 214748364) ||
(result == 214748364 && tmp > 8))) {
result = 2147483648;
} else if ((sign > 0) &&
((result > 214748364) ||
(result == 214748364 && tmp > 7))) {
result = 2147483647;
} else {
result = result * 10 + tmp;
}
}
}
};
class Solution {
public:
int myAtoi(string s) {
Automation automation;
for (auto c : s) {
automation.get_single_char(c);
}
return automation.sign * automation.result;
}
};