首页 > 代码库 > Leetcode: Valid Number

Leetcode: Valid Number

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.

分析:这道题用Deterministic Finite Automata解,逻辑清晰,代码简洁,关键在于正确画出DFA,几个应该注意的case是".1", "1."都是有效的,但"."是无效的。DFA如下:

C++代码如下:

class Solution {public:    bool isNumber(const char *s) {        enum InputType{            INVALID,            SPACE,            SIGN,//+,-            DIGIT,            DOT,            EXP        };        int transitionMatrix[][6] = {            -1, 0, 1, 2, 3, -1,//next state of S0            -1, -1, -1, 2, 3, -1,//next state of S1            -1, 8, -1, 2, 4, 5,//next state of S2            -1, -1, -1, 4, -1, -1,//next state of S3            -1, 8, -1, 4, -1, 5,//next state of S4            -1, -1, 6, 7, -1, -1,//next state of S5            -1, -1, -1, 7, -1, -1,//next state of S6            -1, 8, -1, 7, -1, -1,//next state of S7            -1, 8, -1, -1, -1, -1//next state of S8        };                int state = 0;        while(*s != \0){            InputType itype = INVALID;            if(*s ==  ) itype = SPACE;            else if(*s == + || *s == -) itype = SIGN;            else if(isdigit(*s)) itype = DIGIT;            else if(*s == .) itype = DOT;            else if(*s == e || *s == E) itype = EXP;                        state = transitionMatrix[state][itype];            if(state == -1) return false;            s++;        }                return state == 2 || state == 4 || state == 7 || state == 8;    }};

 

Leetcode: Valid Number