Question :
Validate 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.
Anwser 1 :
class Solution {
public:
bool isNumber(const char *s) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if (s == NULL)
return false;
while(isspace(*s))
s++;
if (*s == '+' || *s == '-')
s++;
bool eAppear = false;
bool dotAppear = false;
bool firstPart = false;
bool secondPart = false;
bool spaceAppear = false;
while(*s != '\0')
{
if (*s == '.')
{
if (dotAppear || eAppear || spaceAppear)
return false;
else
dotAppear = true;
}
else if (*s == 'e' || *s == 'E')
{
if (eAppear || !firstPart || spaceAppear)
return false;
else
eAppear = true;
}
else if (isdigit(*s))
{
if (spaceAppear)
return false;
if (!eAppear)
firstPart = true;
else
secondPart = true;
}
else if (*s == '+' || *s == '-') // behind of e/E
{
if (spaceAppear)
return false;
if (!eAppear || !(*(s-1) == 'e' || *(s-1) == 'E'))
return false;
}
else if (isspace(*s))
spaceAppear = true;
else
return false;
s++;
}
if (!firstPart) {
return false;
} else if (eAppear && !secondPart) {
return false;
}
return true;
}
};
Anwser 2 :
class Solution {
public:
bool isNumber(const char *s) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int mat[11][7] = {
0 ,0 ,0 ,0 ,0 ,0 ,0, // false
0 ,2 ,3 ,0 ,1 ,4 ,0, // 1
0 ,2 ,5 ,6 ,9 ,0 ,10, // 2
0 ,5 ,0 ,0 ,0 ,0 ,0, // 3
0 ,2 ,3 ,0 ,0 ,0 ,0, // 4
0 ,5 ,0 ,6 ,9 ,0 ,10, // 5
0 ,7 ,0 ,0 ,0 ,8 ,0, // 6
0 ,7 ,0 ,0 ,9 ,0 ,10, // 7
0 ,7 ,0 ,0 ,0 ,0 ,0, // 8
0 ,0 ,0 ,0 ,9 ,0 ,10, // 9
10,10,10,10,10,10,10 // 10
};
int i = 0;
int stat = 1;
while(s[i] != '\0')
{
int type = 0;
if(s[i] >= '0' && s[i] <= '9')
type = 1;
else if(s[i] == '.')
type = 2;
else if(s[i] == 'e')
type = 3;
else if(s[i] == ' ')
type = 4;
else if(s[i] == '+' || s[i] == '-')
type = 5;
if(stat == 0)
return false;
stat = mat[stat][type];
i++;
}
stat = mat[stat][6];
if(stat == 10) {
return true;
}
return false;
}
};
参考推荐: