Validate if a given string can be interpreted as a decimal number.
Some examples:
"0" => true
" 0.1 " => true
"abc" => false
"1 a" => false
"2e10" => true
" -90e3 " => true
" 1e" => false
"e3" => false
" 6e-1" => true
" 99e2.5 " => false
"53.5e93" => true
" --6 " => false
"-+3" => false
"95a54e53" => false
Note: It is intended for the problem statement to be ambiguous. You should gather all requirements up front before implementing one. However, here is a list of characters that can be in a valid decimal number:
- Numbers 0-9
- Exponent - "e"
- Positive/negative sign - "+"/"-"
- Decimal point - "."
Of course, the context of these characters also matters in the input.
Update (2015-02-10):
The signature of the C++
function had been updated. If you still see your function signature accepts a const char *
argument, please click the reload button to reset your code definition.
题解:
后面的测试用例真的没意思。。
基本思路就是有限状态转换自动机, 黑色为合法状态。
删除前后的空格,进行判断。
#define INUM 1
#define IEXP 2
#define IPOINT 3
#define ISYMBOL 4
#define IERR 5
#define BEGIN 1
#define NUM 2
#define POINT 3
#define SYMBOL 4
#define EXP 5
#define ESYMBOL 6
#define ENUM 7
#define PNUM 8
#define ERR 9
class Solution {
public:
void judge(int input, int &state) {
switch(input){
case INUM:
if (state == BEGIN || state == SYMBOL || state == NUM) {
state = NUM;
}
else if (state == POINT ||state == PNUM) {
state = PNUM;
}
else if (state == ENUM || state == ESYMBOL || state == EXP) {
state = ENUM;
}
else {
state = ERR;
}
break;
case IEXP:
if (state == NUM || state == PNUM) {
state = EXP;
}
else {
state = ERR;
}
break;
case IPOINT:
if (state == SYMBOL || state == BEGIN) {
state = POINT;
}
else if (state == NUM) {
state = PNUM;
}
else {
state = ERR;
}
break;
case ISYMBOL:
if (state == BEGIN) {
state = SYMBOL;
}
else if (state == EXP) {
state = ESYMBOL;
}
else {
state = ERR;
}
break;
case IERR:
state = ERR;
break;
}
if (state == ERR) {
return;
}
}
void getInput(vector<int> &input, string s) {
for (int i = 0; i < s.length(); i++) {
if (s[i] >= '0' && s[i] <= '9') {
input[i] = INUM;
}
if (s[i] == '-' || s[i] == '+') {
input[i] = ISYMBOL;
}
if (s[i] == 'e') {
input[i] = IEXP;
}
if (s[i] == '.') {
input[i] = IPOINT;
}
}
}
bool isNumber(string s) {
int n = s.length();
if (n == 0) {
return false;
}
int l = 0, r = n - 1;
while (s[l] == ' ') {
l++;
}
while (s[r] == ' ') {
r--;
}
string fix = s.substr(l, r - l + 1);
int state = BEGIN;
int m = fix.length();
if (m == 0) {
return false;
}
vector<int> input(m, IERR);
getInput(input, fix);
for (int i = 0; i < m; i++) {
judge(input[i], state);
if (state == ERR) {
return false;
}
}
if (state == NUM || state == PNUM || state == ENUM) {
return true;
}
return false;
}
};