65. Valid Number

来源:互联网 发布:c语言scanf用法 编辑:程序博客网 时间:2024/05/22 20:28

problem:

Validate if a given string is numeric.

Some examples:
"0" => true
" 0.1 " => true
"abc" => false
"1 a" => false
"2e10" => true

Note: It is intended for the problem statement to be ambiguous. You should gather all requirements up front before implementing one.

这道题几个注意的点:

1.数字的表达方法;

2.对输入的数字进行必要的检测,是否有abc或者中间空格等非法字符;

3.将e前后分开,前面可以有小数点形式,后面不可;

4.数字可以有正负号,“.”前面不一定有数字,后面一定有。


方法使用有限状态机,下面枚举一下各种合法的输入情况:

1.空格+数字+空格

2.空格+点+数字+空格

3.空格+符号+数字+空格

4.空格+符号+点+数字+空格

5.空格+(1,2,3...)+e+(1,2,3...)+空格


组合后的合法字符:

1.数字

2.空格


有限状态机的转移过程:

状态0(起始):

    ->状态0:输入空格

    ->状态1:输入数字,同时不可再接受符号,可接受空格,数字,点,指数,状态1为合法的结束状态

    ->状态3:输入符号时,同时将符号接受标志位改变

    ->状态2:输入点,必须接受数字,其余均非法

    ->非法:输入为指数

状态1(接收数字):

    ->状态1:输入数字

    ->状态4:输入为点,可以接收空格,数字,指数,状态4为合法的结束状态

    ->状态5:输入指数,可以接收符号,数字,不能接收点

状态2(接收点):

    ->状态4:接收数字

状态3(接收符号):

    ->状态1:输入数字,同时不可再接受符号,可接受空格,数字,点,指数,状态1为合法的结束状态

    ->状态2:输入点,必须接受数字,其余均非法

    ->非法:输入为指数

状态4(接收点):

    ->状态4:输入数字,空格

    ->状态5:输入指数

状态5(接收指数):

    ->状态6:输入符号

    ->状态7:输入数字,状态7为合法的结束状态

状态6(接收符号):

    ->状态7:输入数字

状态7(接收数字):

    ->状态7:输入数字

    ->状态8:输入空格

状态8(接收空格):

    ->状态8:输入空格,状态8为合法的结束状态

class Solution {public:    bool isNumber(string s) {        enum InputType        {            INVALID,    // 0            SPACE,      // 1            SIGN,       // 2            DIGIT,      // 3            DOT,        // 4            EXPONENT,   // 5            NUM_INPUTS  // 6        };        int transitionTable[][NUM_INPUTS] =        {            -1,  0,  3,  1,  2, -1,     // next states for state 0            -1,  8, -1,  1,  4,  5,     // next states for state 1            -1, -1, -1,  4, -1, -1,     // next states for state 2            -1, -1, -1,  1,  2, -1,     // next states for state 3            -1,  8, -1,  4, -1,  5,     // next states for state 4            -1, -1,  6,  7, -1, -1,     // next states for state 5            -1, -1, -1,  7, -1, -1,     // next states for state 6            -1,  8, -1,  7, -1, -1,     // next states for state 7            -1,  8, -1, -1, -1, -1,     // next states for state 8        };        int state = 0;        int i = 0;        while(s[i] != '\0')        {            InputType input = INVALID;            if(s[i] == ' ')                input = SPACE;            else if(s[i] == '+' || s[i] == '-')                input = SIGN;            else if((s[i] >= '0') && (s[i] <= '9'))                input = DIGIT;            else if(s[i] == '.')                input = DOT;            else if((s[i] == 'e') || (s[i] == 'E'))                input = EXPONENT;            state = transitionTable[state][input];            if(state == -1)                return false;            else                i++;        }        return state == 1 || state == 4 || state == 7 || state == 8;    }};


0 0