1
1
/*
2
- Author: Annie Kim, anniekim.pku@gmail.com
2
+ Author: Annie Kim, anniekim.pku@gmail.com : Andy, nkuwjg@gmail.com
3
3
Date: May 25, 2013
4
- Update: Sep 30, 2013
4
+ Update: Feb 7, 2015
5
5
Problem: Valid Number
6
6
Difficulty: Hard
7
- Source: http ://leetcode.com/onlinejudge#question_65
7
+ Source: https ://oj. leetcode.com/problems/valid-number/
8
8
Notes:
9
9
Validate if a given string is numeric.
10
10
Some examples:
21
21
22
22
class Solution {
23
23
public:
24
- bool isNumber (const char *s) {
24
+ bool isNumber_1 (const char *s) {
25
25
enum InputType {INVALID, SPACE, SIGN, DIGIT, DOT, EXPONENT};
26
26
int transitionTable[][SPACEEND] =
27
27
{ /* 0 1 2 3 4 5 */
@@ -57,4 +57,26 @@ class Solution {
57
57
bool validFinal[] = {0 , 0 , 0 , 1 , 0 , 0 , 1 , 1 , 1 };
58
58
return validFinal[last];
59
59
}
60
+ bool isNumber_2 (const char *s) {
61
+ bool dot = false , digit = false , exp = false ;
62
+ while (*s == ' ' ) ++s;
63
+ if (*s == ' -' || *s == ' +' ) ++s;
64
+ if (*s == 0 ) return false ;
65
+ for (;*s != ' \0 ' && *s != ' ' ; ++s) {
66
+ if (isdigit (*s)) digit = true ;
67
+ else if (*s == ' e' || *s == ' E' ) {
68
+ if (exp == true || digit == false || *(s+1 ) ==' ' || *(s+1 ) ==' \0 ' ) return false ;
69
+ exp = true ;
70
+ } else if (*s == ' .' ) {
71
+ if (dot == true || exp == true ) return false ;
72
+ if (digit == false && (*(s+1 ) ==' ' || *(s+1 ) ==' \0 ' )) return false ;
73
+ dot = true ;
74
+ } else if (*s == ' -' || *s == ' +' ) {
75
+ if (*(s+1 ) == ' ' || *(s+1 ) == ' \0 ' ) return false ;
76
+ if (*(s-1 ) != ' e' && *(s-1 ) != ' E' ) return false ;
77
+ } else return false ;
78
+ }
79
+ while (*s == ' ' ) ++s;
80
+ return *s == ' \0 ' ;
81
+ }
60
82
};
0 commit comments