-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathNo65.cc
71 lines (64 loc) · 1.97 KB
/
No65.cc
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
/**
* Created by Xiaozhong on 2020/7/22.
* Copyright (c) 2020/7/22 Xiaozhong. All rights reserved.
*/
#include <iostream>
#include <string>
#include <vector>
using namespace std;
/*
* 该解题方法需要参考 编译原理的 DFA(有限状态机)
*/
class Solution {
public:
bool isNumber(string s) {
if (s.empty()) return false;
int n = s.size();
int state = 0;
vector<int> finals({0, 0, 0, 1, 0, 1, 1, 0, 1}); // 合法的终止状态
// 该状态转换矩阵需要依据 DFA 来理解
vector<vector<int>> transfer({
{0, 1, 6, 2, -1, -1},
{-1, -1, 6, 2, -1, -1},
{-1, -1, 3, -1, -1, -1},
{8, -1, 3, -1, 4, -1},
{-1, 7, 5, -1, -1, -1},
{8, -1, 5, -1, -1, -1},
{8, -1, 6, 3, 4, -1},
{-1, -1, 5, -1, -1, -1},
{8, -1, -1, -1, -1, -1},
});
for (int i = 0; i < n; ++i) {
state = transfer[state][_make(s[i])];
if (state < 0) return false;
}
return finals[state];
}
private:
int _make(const char &c) {
switch (c) {
case ' ':
return 0;
case '+':
return 1;
case '-':
return 1;
case '.':
return 3;
case 'e':
return 4;
default:
return _number(c);
}
}
int _number(const char &c) {
if (c >= '0' && c <= '9')
return 2;
else
return 5;
}
};
int main() {
Solution s;
cout << s.isNumber("0") << endl;
}