[LeetCode]Valid Number
Valid Number
alidate 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 class Solution 2 { 3 public: 4 bool isNumber(string s) 5 { 6 enum InputType 7 { 8 INVALID, // 0 9 SPACE, // 1 10 SIGN, // 2 11 DIGIT, // 3 12 DOT, // 4 13 EXPONENT, // 5 14 NUM_INPUTS // 6 15 }; 16 17 int transitionTable[][NUM_INPUTS] = 18 { 19 -1, 0, 3, 1, 2, -1, // next states for state 0 20 -1, 8, -1, 1, 4, 5, // next states for state 1 21 -1, -1, -1, 4, -1, -1, // next states for state 2 22 -1, -1, -1, 1, 2, -1, // next states for state 3 23 -1, 8, -1, 4, -1, 5, // next states for state 4 24 -1, -1, 6, 7, -1, -1, // next states for state 5 25 -1, -1, -1, 7, -1, -1, // next states for state 6 26 -1, 8, -1, 7, -1, -1, // next states for state 7 27 -1, 8, -1, -1, -1, -1, // next states for state 8 28 }; 29 int i=0; 30 int state = 0; 31 while (i<s.length()) 32 { 33 InputType inputType = INVALID; 34 if (isspace(s[i])) 35 inputType = SPACE; 36 else if (s[i] == '+' || s[i] == '-') 37 inputType = SIGN; 38 else if (isdigit(s[i])) 39 inputType = DIGIT; 40 else if (s[i] == '.') 41 inputType = DOT; 42 else if (s[i] == 'e' || s[i] == 'E') 43 inputType = EXPONENT; 44 45 state = transitionTable[state][inputType]; 46 47 if (state == -1) 48 return false; 49 else 50 i++; 51 } 52 53 return state == 1 || state == 4 || state == 7 || state == 8; 54 } 55 };