1
+ // NFA
1
2
class Solution {
2
3
public:
4
+ bool accept (const char * s, int & i, string expected) {
5
+ for (int j = 0 ; j < expected.size (); j++) {
6
+ if (s[i] == expected[j]) {
7
+ i += 1 ;
8
+ return true ;
9
+ }
10
+ }
11
+ return false ;
12
+ }
13
+
14
+ bool acceptRun (const char * s, int & i, string expected) {
15
+ bool found = false ;
16
+ int count = 0 ;
17
+ while (s[i] != ' \0 ' ) {
18
+ found = false ;
19
+ for (int j = 0 ; j < expected.size (); j++) {
20
+ if (s[i] == expected[j]) {
21
+ i++;
22
+ count++;
23
+ found = true ;
24
+ }
25
+ }
26
+ if (!found) {
27
+ break ;
28
+ }
29
+ }
30
+ if (count > 0 ) {
31
+ return true ;
32
+ }
33
+ return false ;
34
+ }
35
+
3
36
bool isNumber (const char *s) {
4
- // Start typing your C/C++ solution below
5
- // DO NOT write int main() function
37
+ string digits (" 0123456789" );
6
38
7
- while (*s != ' \0 ' && *s == ' ' ) s += 1 ;
8
- if (*s == ' \0 ' ) return false ;
39
+ int i = 0 ;
9
40
10
- const char *e = s + strlen (s) - 1 ;
11
- while (s <= e && *e == ' ' ) e -= 1 ;
41
+ acceptRun (s, i, " " );
12
42
13
- bool is_digit = false ;
14
- bool has_dot = false ;
15
- bool has_exp = false ;
43
+ bool beforedot = false ;
44
+ bool afterdot = false ;
16
45
17
- if (*s == ' +' || *s == ' -' ) s += 1 ;
46
+ accept (s, i, " +-" );
47
+ beforedot = acceptRun (s, i, digits);
18
48
19
- while (s <= e) {
20
- if (' 0' <= *s && *s <= ' 9' ) {
21
- is_digit = true ;
22
- }
23
- else if (*s == ' .' ) {
24
- if (has_dot || has_exp)
25
- return false ;
26
- has_dot = true ;
49
+ if (accept (s, i, " ." )) {
50
+ if (acceptRun (s, i, digits)) {
51
+ afterdot = true ;
27
52
}
28
- else if (*s == ' e' ) {
29
- if (!is_digit || has_exp)
30
- return false ;
31
- has_exp = true ;
32
- is_digit = false ;
53
+ }
54
+
55
+ if (!beforedot && !afterdot) {
56
+ return false ;
57
+ }
58
+
59
+ if (accept (s, i, " eE" )) {
60
+ accept (s, i, " +-" );
61
+ if (!acceptRun (s, i, digits)) {
62
+ return false ;
33
63
}
34
- else if (*s == ' +' || *s == ' -' ) {
35
- if (*(s-1 ) != ' e' )
36
- return false ;
64
+ }
65
+
66
+ while (s[i] != ' \0 ' ) {
67
+ if (s[i] != ' ' ) {
68
+ return false ;
37
69
}
38
- else return false ;
39
- s += 1 ;
70
+ i++;
40
71
}
41
- return is_digit ;
72
+ return true ;
42
73
}
43
- };
74
+ };
0 commit comments