Leetcode -- Valid Number

Valid Number

Solve with Automata

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
class Solution {

public:
inline void initPos() {
memset(pos, -1, 128);
memset(pos + 48, 1, 10);
pos['+'] = pos['-'] = 0;
pos['e'] = pos['E'] = 3;
pos['.'] = 2;
pos[' '] = 4;
}

bool isNumber(string s) {
int state = 0;
initPos();
for(char c: s)
if (!(pos[c] >= 0 && 0 <= (state = trans[state][pos[c]])))
return false;
return trans[state][5];
}

private:
// +/- d . e/E space can_accept
int trans[11][6] = {
{ 1, 2, 8, -1, 0, 0 },
{ -1, 2, 8, -1, -1, 0 },
{ -1, 2, 3, 5, 10, 1 },
{ -1, 4, -1, 5, 10, 1 },
{ -1, 4, -1, 5, 10, 1 },
{ 6, 7, -1, -1, -1, 0 },
{ -1, 7, -1, -1, 10, 0 },
{ -1, 7, -1, -1, 10, 1 },
{ -1, 9, -1, -1, -1, 0 },
{ -1, 9, -1, 5, 10, 1 },
{ -1, -1, -1, -1, 10 ,1}
};

char pos[128];
};
Contents
  1. 1. Valid Number
    1. 1.1. Solve with Automata