美文网首页
剑指 Offer 20. 表示数值的字符串

剑指 Offer 20. 表示数值的字符串

作者: 漫行者_ | 来源:发表于2021-08-26 00:05 被阅读0次

剑指 Offer 20. 表示数值的字符串

这道题采用状态机来做,状态机的最大难度就是写出对应的数组。
以后匹配字符格式的可以采用状态机来做。

cd98b43df05d7dac40890f748e32e51.jpg
开始状态为state=0,
本题要注意空格的情况,最后还可以有空格,也就是图中的状态3
代码如下:
class Solution {
    public boolean isNumber(String s) {
        int[][] stateTable = {
                {0, 2,  1, 4, -1, -1},
                {-1, 2, -1, 4, -1, -1},
                {3, 2, -1, 6, 7, -1},
                {3, -1, -1, -1, -1, -1},
                {-1, 5, -1, -1, -1, -1},
                {3, 5, -1, -1, 7, -1},
                {3, 6, -1, -1, 7, -1},
                {-1, 8, 9, -1, -1, -1},
                {3, 8, -1, -1, -1, -1},
                {-1, 8, -1, -1, -1, -1}
        };
        int state = 0;
        List<Integer> legalState = new ArrayList<Integer>() {{
            add(2);
            add(3);
            add(5);
            add(8);
            add(6);
        }};
        for (int i = 0; i < s.length(); i++) {
            state = stateTable[state][getCol(s.charAt(i))];
            if (state == -1) return false;
        }
        if (legalState.contains(state)) return true;
        return false;
    }

    public int getCol(char c){
        if (c=='+'||c=='-') return 2;
        if (c>='0'&&c<='9') return 1;
        if (c=='.') return 3;
        if (c=='E'||c=='e') return 4;
        if (c==' ') return 0;
        return 5;
    }
}

相关文章

网友评论

      本文标题:剑指 Offer 20. 表示数值的字符串

      本文链接:https://www.haomeiwen.com/subject/kelyiltx.html