LeetCode question 8: Convert string to integer (atoi) (use DFA state transition method to answer)

This question can be answered by the method of automata (DFA), and the DFA method is actually answered by state transition.

According to the title, we can divide the solution process into four states:

  • initial state - start - 0

  • sign state - sign - 1

  • number state - num - 2

  • End Status - end - 3

Record these four states as 0,1,2,3 respectively. The program starts from the initial state 0 and stops when it reaches the terminal state 3.

Starting from the initial state, traverse the string s. There are four types of characters read: spaces, sign bits, numbers, and other characters.

When these four characters are encountered in each state:

  • initial state 0

  • When a space is encountered, the state remains unchanged and the next character is read directly;

  • Encounter a sign bit, record the read symbol, and switch the state to symbol state 1;

  • Encounter a number, record the number, and switch the state to digital state 2;

  • When other characters are encountered, the state is switched to termination state 3.

  • symbol state 1

  • When a space is encountered, the state is switched to termination state 3;

  • When the sign bit is encountered, the state is switched to the termination state 3; (when s="+-12", the output should be 0, so two sign bits are encountered to terminate)

  • Encounter a number, record the number, and switch the state to digital state 2;

  • When other characters are encountered, the state is switched to termination state 3.

  • digital state 2

  • When a space is encountered, the state is switched to termination state 3;

  • When a sign bit is encountered, switch the state to termination state 3;

  • Encounter a number, record the number, and the state remains unchanged;

  • When other characters are encountered, the state is switched to termination state 3.

  • Termination state 3

  • Directly terminate the traversal and return the obtained result.

Therefore, the state transition function can be obtained:

space

sign bit

number

other

0

initial start

0

1

2

3

1

symbol sign

3

3

2

3

2

number num

3

3

2

3

3

end end

With the state transition function, we can easily write the solution process:

Here is the answer using Python:

class Solution:
    def myAtoi(self, s: str) -> int:
        """使用DFA方法实现atoi"""

        sign_dist = {'+':1, '-':-1} # 符号标识种子
        num_seed = '0123456789'     # 数字字符种子

        sign = 1    # 符号标识,1为正,-1为负
        status = 0  # 初始状态为0
        # 0-初始start  1-符号sign  2-数字num  3-终止end

        integer = 0 # 最终要返回的整数

        # 遍历字符串s
        for c in s:
            # 0-初始状态start 
            if status == 0:
                if c == ' ':
                    continue
                elif c == '+' or c == '-':
                    sign = sign_dist[c]
                    status = 1
                elif c in num_seed:
                    integer = 10*integer + int(c)
                    status = 2
                else:
                    status = 3
            
            # 1-符号状态sign
            elif status == 1:
                if c == ' ' or c == '+' or c == '-':
                    status = 3
                elif c in num_seed:
                    integer = 10*integer + int(c)
                    status = 2
                else:
                    status = 3

            # 2-数字状态num
            elif status == 2:
                if c == ' ' or c == '+' or c == '-':
                    status = 3
                elif c in num_seed:
                    integer = 10*integer + int(c)                   
                    # 判断是否越界,越界直接返回边界值
                    if integer * sign < -1 * 2**31:
                        return -1 * 2**31
                    elif integer * sign > 2**31 - 1:
                        return 2**31 - 1
                else:
                    status = 3

            # 3-终止状态end
            elif status == 3:
                break

        # 返回最终结果
        return integer * sign

Here is the solution process using C++:

class Solution {
public:
    int myAtoi(string s) {
        // 使用DFA实现atoi

        string sign_seed = "+-";    // 符号标识种子

        int sign = 1;         // 符号标识
        int status = 0;       // 初始状态为0
        // 0-初始start  1-符号sign  2-数字num  3-终止end

        long long integer = 0;// 最终要返回的整数

        // 遍历字符串s
        for(int i = 0; i < s.size(); i++){
            // 通过switch进入不同的状态
            switch(status){
            // 0-初始状态start
            case 0:
                if(s[i] == ' '){
                    break;
                }
                else if(s[i] == sign_seed[0]){
                    sign = 1;
                    status = 1;
                }
                else if(s[i] == sign_seed[1]){
                    sign = -1;
                    status = 1;
                }
                else if(s[i] >= '0' && s[i] <= '9'){
                    integer = 10 * integer + (s[i] - '0');
                    status = 2;
                }
                else{
                    status = 3;
                }
                break;

            // 1-符号状态sign
            case 1:
                if(s[i] == ' '){
                    status = 3;
                }
                else if(s[i] == sign_seed[0] || s[i] == sign_seed[1]){
                    status = 3;
                }
                else if(s[i] >= '0' && s[i] <= '9'){
                    integer = 10 * integer + (s[i] - '0');
                    status = 2;
                }
                else{
                    status = 3;
                }
                break;

            // 2-数字状态num
            case 2:
                if(s[i] == ' '){
                    status = 3;
                }
                else if(s[i] == sign_seed[0] || s[i] == sign_seed[1]){
                    status = 3;
                }
                else if(s[i] >= '0' && s[i] <= '9'){
                    integer = 10 * integer + (s[i] - '0');
                    // 判断是否越界,越界直接返回边界值
                    if(integer * sign > 2147483647){
                        return 2147483647;
                    }
                    else if(integer * sign < -2147483648){
                        return -2147483648;
                    }
                }
                else{
                    status = 3;
                }
                break;

            // 3-终止状态end
            case 3:
                break;
            }
            if(status == 3){
                break;
            }
        }

        return integer * sign;
    }
};

Guess you like

Origin blog.csdn.net/lyb06/article/details/129465915