0%

valid-number

题目描述

实现一个函数用来判断字符串是否表示数值(包括整数和小数)。例如,字符串”+100”、”5e2”、”-123”、”3.”、”.200”、”0123”都表示数值,但”12e”、”1a3.14”、”1.2.3”、”+-5”、”-1E-16”及”12e+5.4”都不是。

题解

有限状态机求解。

初态:0

终态:2、3、7、8

0(blank) 1(sign) 2(digit) 3(dot) 4(e)
-1 -1 -1 -1 -1 -1
0 0 1 2 4 -1
1 -1 -1 2 4 -1
2 8 -1 2 3 5
3 8 -1 3 -1 5
4 -1 -1 3 -1 -1
5 -1 6 7 -1 -1
6 -1 -1 7 -1 -1
7 8 -1 7 -1 -1
8 8 -1 -1 -1 -1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
int type(char c)
{
if (c == ' ')return 0;
if (c == '-' || c == '+')return 1;
if (c >= '0'&&c <= '9')return 2;
if (c == '.')return 3;
if (c == 'e' || c == 'E')return 4;
return -1;
}
bool isNumber(string s) {
int len = s.length();
int table[9][5] = { { 0,1,2,4,-1 },{ -1,-1,2,4,-1 },{ 8,-1,2,3,5 },{ 8,-1,3,-1,5 },{ -1,-1,3,-1,-1 },{ -1,6,7,-1,-1 },{ -1,-1,7,-1,-1 },{ 8,-1,7,-1,-1 },{ 8,-1,-1,-1,-1 } };
int status = 0;
for (int i = 0; i<len; i++)
{
int input = type(s[i]);
if (input == -1)return false;
status = table[status][input];
if (status == -1)return false;
}
if (status == 2 || status == 3 || status == 7 || status == 8)return true;
return false;
}