> 簡潔易懂講清原理,講不清你來打我~

輸入字串,輸出整數
![在這裡插入圖片描述](https://img-blog.csdnimg.cn/4feb56d86fca437a98f1e7f18d4288c3.png)
![](https://img-blog.csdnimg.cn/78452fd60d9744ce9dca1924025df944.png)
![在這裡插入圖片描述](https://img-blog.csdnimg.cn/9e762814bac5404cb3700e76515a995b.png)
![在這裡插入圖片描述](https://img-blog.csdnimg.cn/a9e89cb153e34f53b1f5d90062b6a806.png)
![在這裡插入圖片描述](https://img-blog.csdnimg.cn/4f3909035de74f8196d18d38f204e6f8.png)

> 有限狀態機

簡單的思路
建立狀態轉換圖和狀態轉換表,雜湊表儲存狀態轉移表的行索引和新的狀態,通過行索引的原始狀態和列索引的字元獲得新的狀態狀態,遇到數字放入結果的個位

準確的定義
state是當前的狀態
table是狀態轉換表
positive是當前計算結果的絕對值
c是當前的字元
isPositive是結果是否為正數
![在這裡插入圖片描述](https://img-blog.csdnimg.cn/70dfd609c0914780b77cdd0d626554b3.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3pob3V6aWhvbmc=,size_16,color_FFFFFF,t_70)

```cpp
class Solution {
public:
int myAtoi(string str) {
for (char c : str)change(c);
if(isPositive)return positive;
else return -positive;
}
void change(char c) {
state = table[state][getCol(c)];
if (state == "in_number") {
positive = positive * 10 + c - '0';
positive = isPositive? min(positive, (long long)INT_MAX) : min(positive, -(long long)INT_MIN);
}
else if (state == "signed"&&c=='-')isPositive=false;
}
int getCol(char c) {
if (isspace(c)) return 0;
if (c == '+' || c == '-') return 1;
if (isdigit(c)) return 2;
return 3;
}
private:
string state = "start";
int isPositive = 1;
long long positive = 0;
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"}}
};
};
```

踩過的坑

```cpp
long long positive = 0;

positive = isPositive? min(positive, (long long)INT_MAX) : min(positive, -(long long)INT_MIN);

else if (state == "signed"&&c=='-')isPositive=false;
```

1

> 喜歡簡潔易懂還能講清楚原理部落格的小夥伴就關注關注這個非常高產的博主呀,下次再會~