> 簡潔易懂講清原理,講不清你來打我~
輸入字串,輸出整數





> 有限狀態機
簡單的思路
建立狀態轉換圖和狀態轉換表,雜湊表儲存狀態轉移表的行索引和新的狀態,通過行索引的原始狀態和列索引的字元獲得新的狀態狀態,遇到數字放入結果的個位
準確的定義
state是當前的狀態
table是狀態轉換表
positive是當前計算結果的絕對值
c是當前的字元
isPositive是結果是否為正數

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