天天看點

LeetCode 8 - 字元串轉換整數

題目描述

8. 字元串轉換整數 (atoi)

解法一:自動機(C++)

LeetCode 8 - 字元串轉換整數

詳細參考 字元串轉換整數 (atoi)

class Automation{
    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) {
        Automation automation;
        for(char c: str)
            automation.get(c);
        return automation.sign*automation.ans;
    }
};
           

解法二:資料流(C++)

class Solution {
public:
    int myAtoi(string str) {
        long long  num = 0;
        istringstream str_1(str);
        str_1 >> num;
        if(num>INT_MAX)
            return INT_MAX;
        else if(num<INT_MIN)
            return INT_MIN;
        else return num;
    }
};
           

解法三:正則(Python)

class Solution:
    def myAtoi(self, str: str) -> int:
        INT_MAX = 2147483647 
        INT_MIN = -2147483648
        str = str.lstrip()
        num_re = re.compile(r'^[\+\-]?\d+')
        num = num_re.findall(str)
        num = int(*num) # 由于傳回的是個清單,解包并且轉換成整數
        return max(min(num, INT_MAX), INT_MIN)