Skip to content

Commit 26b1a32

Browse files
committed
3
1 parent 4f9f9bf commit 26b1a32

File tree

1 file changed

+61
-30
lines changed

1 file changed

+61
-30
lines changed

ValidNumber/ValidNumber.cpp

+61-30
Original file line numberDiff line numberDiff line change
@@ -1,43 +1,74 @@
1+
// NFA
12
class Solution {
23
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+
336
bool isNumber(const char *s) {
4-
// Start typing your C/C++ solution below
5-
// DO NOT write int main() function
37+
string digits("0123456789");
638

7-
while (*s != '\0' && *s == ' ') s += 1;
8-
if (*s == '\0') return false;
39+
int i = 0;
940

10-
const char *e = s + strlen(s) - 1;
11-
while (s <= e && *e == ' ') e -= 1;
41+
acceptRun(s, i, " ");
1242

13-
bool is_digit = false;
14-
bool has_dot = false;
15-
bool has_exp = false;
43+
bool beforedot = false;
44+
bool afterdot = false;
1645

17-
if (*s == '+' || *s == '-') s += 1;
46+
accept(s, i, "+-");
47+
beforedot = acceptRun(s, i, digits);
1848

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;
2752
}
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;
3363
}
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;
3769
}
38-
else return false;
39-
s += 1;
70+
i++;
4071
}
41-
return is_digit;
72+
return true;
4273
}
43-
};
74+
};

0 commit comments

Comments
 (0)