1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103
| class Solution { enum State { STATE_INITIAL, STATE_INT_SIGN, STATE_INTEGER, STATE_POINT, STATE_POINT_WITHOUT_INT, STATE_FRACTION, STATE_EXP, STATE_EXP_SIGN, STATE_EXP_NUMBER, STATE_END };
enum CharType { CHAR_NUMBER, CHAR_EXP, CHAR_POINT, CHAR_SIGN, CHAR_SPACE, CHAR_ILLEGAL };
CharType toCharType(char ch) { if (ch >= '0' && ch <= '9') return CHAR_NUMBER; else if (ch == 'e' || ch == 'E') return CHAR_EXP; else if (ch == '.') return CHAR_POINT; else if (ch == '+' || ch == '-') return CHAR_SIGN; else if (ch == ' ') return CHAR_SPACE; else return CHAR_ILLEGAL; } public: bool isNumber(string s) { unordered_map<State, unordered_map<CharType, State>> transfer { {STATE_INITIAL, { {CHAR_SPACE, STATE_INITIAL}, {CHAR_NUMBER, STATE_INTEGER}, {CHAR_POINT, STATE_POINT_WITHOUT_INT}, {CHAR_SIGN, STATE_INT_SIGN} }}, {STATE_INT_SIGN, { {CHAR_NUMBER, STATE_INTEGER}, {CHAR_POINT, STATE_POINT_WITHOUT_INT} }}, {STATE_INTEGER, { {CHAR_NUMBER, STATE_INTEGER}, {CHAR_EXP, STATE_EXP}, {CHAR_POINT, STATE_POINT}, {CHAR_SPACE, STATE_END} }}, {STATE_POINT, { {CHAR_NUMBER, STATE_FRACTION}, {CHAR_EXP, STATE_EXP}, {CHAR_SPACE, STATE_END} }}, {STATE_POINT_WITHOUT_INT, { {CHAR_NUMBER, STATE_FRACTION} }}, {STATE_FRACTION, { {CHAR_NUMBER, STATE_FRACTION}, {CHAR_EXP, STATE_EXP}, {CHAR_SPACE, STATE_END} }}, {STATE_EXP, { {CHAR_NUMBER, STATE_EXP_NUMBER}, {CHAR_SIGN, STATE_EXP_SIGN} }}, {STATE_EXP_SIGN, { {CHAR_NUMBER, STATE_EXP_NUMBER} }}, {STATE_EXP_NUMBER, { {CHAR_NUMBER, STATE_EXP_NUMBER}, {CHAR_SPACE, STATE_END} }}, {STATE_END, { {CHAR_SPACE, STATE_END} }} };
int len = s.length(); State st = STATE_INITIAL; for (int i = 0; i < len; ++i) { CharType chtype = toCharType(s[i]); if (transfer[st].find(chtype) == transfer[st].end()) { return false; } else { st = transfer[st][chtype]; } } return st == STATE_INTEGER || st == STATE_POINT || st == STATE_FRACTION || st == STATE_EXP_NUMBER || st == STATE_END; } };
|