/**************************************************************************
*
* 65. [Valid Number](https://leetcode.com/problems/valid-number/)
*
* For example, all the following are valid numbers:
* ["2", "0089", "-0.1", "+3.14", "4.", "-.9", "2e10", "-90E3", "3e+7", "+6e-1", "53.5e93", "-123.456e789"],
* while the following are not valid numbers: ["abc", "1a", "1e", "e3", "99e2.5", "--6", "-+3", "95a54e53"].
* Given a string s, return true if s is a valid number.
*
**************************************************************************/
///
///
/// Approach 1:
bool isNumber(char * s){
if (NULL == s) return false;
int len = strlen(s);
int index = 0; //index of s
int nums = 0; //nums of digits
while (s[index] == ' ')
index++;
while (s[index] == '+' || s[index] == '-')
index++;
while (isdigit(s[index]))
index++, nums++;
if (s[index] == '.')
index++;
while (isdigit(s[index]))
index++, nums++;
if (nums == 0)
return false;//小数点前后均没有数字、e前面没有数字
if (s[index] == 'e' || s[index] == 'E') {
index++;
nums = 0;
if (s[index] == '+' || s[index] == '-')
index++;
while (isdigit(s[index]))
index++, nums++;
if (nums == 0)
return false; //e后面没数字
}
while (s[index] == ' ')
index++;
return len == index;
}
///
///
/// Approach 2: Use Deterministic Finite Automata method
bool isNumber(char* s) {
if (NULL == s) return false;
int len = strlen(s);
typedef enum {
INVALID, // 0
SPACE, // 1
SIGN, // 2
DIGIT, // 3
DOT, // 4
EXPONENT, // 5
NUM_INPUTS // 6
} InputType;
//二维数组
const 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;
for (int i = 0; i < len; i++) {
char ch = s[i];
InputType inputType = INVALID;
if (isspace(ch))
inputType = SPACE;
else if (ch == '+' || ch == '-')
inputType = SIGN;
else if (isdigit(ch))
inputType = DIGIT;
else if (ch == '.')
inputType = DOT;
else if (ch == 'e' || ch == 'E')
inputType = EXPONENT;
// Get next state from current state and input symbol
state = transitionTable[state][inputType];
// Invalid input
if (state == -1) return false;
}
// If the current state belongs to one of the accepting (final) states,
// then the number is valid
return state == 1 || state == 4 || state == 7 || state == 8;
}