|
| 1 | +// Time: O(n) |
| 2 | +// Space: O(1) |
| 3 | + |
| 4 | +// automata: http://images.cnitblog.com/i/627993/201405/012016243309923.png |
| 5 | +class Solution { |
| 6 | +public: |
| 7 | + bool isNumber(string s) { |
| 8 | + enum InputType { |
| 9 | + INVALID, // 0 |
| 10 | + SPACE, // 1 |
| 11 | + SIGN, // 2 |
| 12 | + DIGIT, // 3 |
| 13 | + DOT, // 4 |
| 14 | + EXPONENT, // 5 |
| 15 | + NUM_INPUTS // 6 |
| 16 | + }; |
| 17 | + int transitionTable[][NUM_INPUTS] = { |
| 18 | + -1, 0, 3, 1, 2, -1, // next states for state 0 |
| 19 | + -1, 8, -1, 1, 4, 5, // next states for state 1 |
| 20 | + -1, -1, -1, 4, -1, -1, // next states for state 2 |
| 21 | + -1, -1, -1, 1, 2, -1, // next states for state 3 |
| 22 | + -1, 8, -1, 4, -1, 5, // next states for state 4 |
| 23 | + -1, -1, 6, 7, -1, -1, // next states for state 5 |
| 24 | + -1, -1, -1, 7, -1, -1, // next states for state 6 |
| 25 | + -1, 8, -1, 7, -1, -1, // next states for state 7 |
| 26 | + -1, 8, -1, -1, -1, -1, // next states for state 8 |
| 27 | + }; |
| 28 | + |
| 29 | + int state = 0; |
| 30 | + for (const auto& c: s) { |
| 31 | + InputType inputType = INVALID; |
| 32 | + if (isspace(c)) { |
| 33 | + inputType = SPACE; |
| 34 | + } else if (c == '+' || c == '-') { |
| 35 | + inputType = SIGN; |
| 36 | + } else if (isdigit(c)) { |
| 37 | + inputType = DIGIT; |
| 38 | + } else if (c == '.') { |
| 39 | + inputType = DOT; |
| 40 | + } else if (c == 'e' || c == 'E') { |
| 41 | + inputType = EXPONENT; |
| 42 | + } |
| 43 | + // Get next state from current state and input symbol |
| 44 | + state = transitionTable[state][inputType]; |
| 45 | + |
| 46 | + // Invalid input |
| 47 | + if (state == -1) { |
| 48 | + return false; |
| 49 | + } |
| 50 | + } |
| 51 | + // If the current state belongs to one of the accepting (final) states, |
| 52 | + // then the number is valid |
| 53 | + return state == 1 || state == 4 || state == 7 || state == 8; |
| 54 | + } |
| 55 | +}; |
| 56 | + |
| 57 | +#include <regex> |
| 58 | +class Solution_TLE { |
| 59 | +public: |
| 60 | + bool isNumber(string s) { |
| 61 | + regex e("^\\s*[\\+-]?((\\d+(\\.\\d*)?)|\\.\\d+)([eE][\\+-]?\\d+)?\\s*$"); |
| 62 | + return regex_match(s, e); |
| 63 | + } |
| 64 | +}; |
0 commit comments