本文出自:http://blog.csdn.net/svitter
DFA:
使用了表驱动法;
构造的表如下:
num | . | E | +/- | other | |
---|---|---|---|---|---|
0 | 1 | 6 | - | - | - |
1 | 1 | 2 | 5 | - | - |
2 | 2 | - | 3 | - | - |
3 | - | - | - | 4 | -- |
4 | 5 | - | - | - | - |
5 | 5 | - | - | - | - |
6 | 2 | - | - | - | - |
7 | |||||
代码如下:
//============================================================================
// Name : compliler.cpp
// Author : Vit
// Version :
// Copyright : Your copyright notice
// Description : Hello World in C++, Ansi-style
//============================================================================
#include <iostream>
#include <cstdio>
#include <string.h>
#include <stdlib.h>
using namespace std;
int State[8][5];
//set final accept
const bool Acsta[7] =
{ 0, 1, 1, 0, 0, 1, 0, };
//JudgeNum
int JudgeNum(char &ch)
{
if (ch >= '0' && ch <= '9')
return 0;
else if (ch == '.')
return 1;
else if (ch == 'E')
return 2;
else if (ch == '+' || ch == '-')
return 3;
else
return 4;
}
//init the table
void init()
{
//set error state
for (int i = 0; i < 8; i++)
for (int j = 0; j < 5; j++)
{
State[i][j] = 7;
}
//set table
State[0][0] = 1;
State[0][1] = 6;
State[1][0] = 1;
State[1][1] = 2;
State[1][2] = 5;
State[2][0] = 2;
State[2][2] = 3;
State[3][3] = 4;
State[4][0] = 5;
State[5][0] = 5;
State[6][0] = 2;
}
//利用函数调用来读
char* Judge(char *str)
{
int i, j; //work point
//var
int len = strlen(str); //计算串长度
char *t = new char[2000]; //返回串
memset(t, '\0', 2000);
int cur; //字符下标
char ch; //字符
int state; //状态
int beg; //开始
int endd; //结束
bool change;
//start
for (i = 0; i < len; i++)
{
beg = cur = i;
ch = str[i];
state = 0;
endd = beg;
change = false;
while (state != 7)
{
state = State[state][JudgeNum(ch)];
if (Acsta[state])
{
endd = cur; //记录最后一次符合状态的下标
change = true;
}
ch = str[++cur];
if (change)
{
if ((endd - beg) >= strlen(t))
{
for (j = beg; j <= endd; j++)
{
t[j - beg] = str[j];
}
}
change = false;
}
}
}
return t;
}
int main(void)
{
char *t;
char str[2000];
init();
freopen("test", "r", stdin);
while (~scanf("%s", str))
{
t = Judge(str);
printf("%s\n", t);
}
return 0;
}