能提取本题有效数字的状态机:start → 空白 → 符号 → 数字 → 其他字符 → end,其中空白、数字、其他符号有自旋边。

用长度为4的位集合来记录遍历字符过程中的上一个状态,0000为初始状态,由低位到高位依次对应空白、符号、数字、其他字符的存在情况,置 1 表示对应子串存在


public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     *
     * @param s string字符串
     * @return int整型
     */
    public int StrToInt (String s) {
        if (s == null || s.length() == 0) return 0;

        /**
         * 能提取本题有效数字的状态机:start → 空白 → 符号 → 数字 → 其他字符 → end,
         * 其中空白、数字、其他符号有自旋边。用长度为4的位集合来记录遍历字符过程中的上一
         * 个状态,0000为初始状态,由低位到高位依次对应空白、符号、数字、其他字符的存在
         * 情况,置 1 表示对应子串存在。
         */

        // 获取数字子串
        int lastState = 0;// 记录上一个状态。

        boolean negative = false;// 是否是负数
        int start = 0;// 数字部分的开始位置
        int end = 0;// 数字部分的结束位置,不包含。

        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);

            if (Character.isWhitespace(c)) {
                if (lastState == 0){// 空白 置1。
                    lastState = 1;
                    continue;
                }
                if (lastState == 1){
                    continue;
                }
            }
            if (c == '+' || c == '-'){
                if (lastState <= 1){// 符号 置1。
                    if (c == '-'){
                        negative = true;
                    }
                    lastState |= 2;
                    continue;
                }
            }
            if (Character.isDigit(c)){// 当前字符为数字字符
                if (lastState <= 3){// 数字 置1
                    start = i;
                    lastState |= 4;
                    continue;
                }
                if ((lastState >>> 2) == 1) {
                    continue;
                }
            }
            if (!Character.isDigit(c)){
                if ((lastState >>> 2) == 1){
                    end = i;
                    lastState |= 8;
                    break;
                }
            }
            return 0;// 不符合状态机的检查过程,无法提取有效数字,直接返回。
        }

        if ((lastState >>> 2) == 1){// 这种情况肯定是遍历完了整个字符串。
            end = s.length();
        }
        
        if (start >= end){
            return 0;
        }
        if (negative){
            --start;
        }

        // 转换为数字返回
        int result = 0;
        try{
            result = Integer.parseInt(s.substring(start, end));
        }catch (NumberFormatException e){
            result = negative ? Integer.MIN_VALUE : Integer.MAX_VALUE;
        }

        return result;
    }
}