package com.algorithm.str;/**
* 自动机实现表示数值的字符串 组成部分:空格、符号、数字、点、指数
*
* @author wxq
*
*/publicclassAC2{enum InputType {
START,// 0
SPACE,// 1
SIGN,// 2
DIGIT,// 3
DOT,// 4
EXPONENT // 5// NUM_INPUTS // 6};//定义状态迁移表, 不画图理解有点困难//状态迁移表矩阵:每一行为当前状态的下一状态的多种取值privatestaticint transitionTable[][]={//start SPACE SIGN DIGIT DOT E{-1,0,3,1,2,-1},// next states for state 0 {-1,8,-1,1,4,5},// next states for state 1{-1,-1,-1,4,-1,-1},// next states for state 2{-1,-1,-1,1,2,-1},// next states for state 3{-1,8,-1,4,-1,5},// next states for state 4{-1,-1,6,7,-1,-1},// next states for state 5{-1,-1,-1,7,-1,-1},// next states for state 6{-1,8,-1,7,-1,-1},// next states for state 7{-1,8,-1,-1,-1,-1},// next states for state 8};/**
* 有限状态自动机实现
*
* @param string
* @return
*/staticbooleanisNumeric(char[] string){int state =0;for(int i =0; i < string.length; i++){char c = string[i];
InputType inputType = InputType.START;//设置初始值//如果输入字符为空格if(" ".equals(c)){
inputType = InputType.SPACE;}//如果输入字符为+-号elseif(c =='+'|| c =='-'){
inputType = InputType.SIGN;}//如果输入字符为数字elseif(c >='0'&& c <='9'){
inputType = InputType.DIGIT;}//如果输入字符为点elseif(c =='.'){
inputType = InputType.DOT;}//如果输入字符为e Eelseif(c =='e'|| c =='E'){
inputType = InputType.EXPONENT;}
state = transitionTable[state][inputType.ordinal()];if(state ==-1)returnfalse;}return state ==1|| state ==4|| state ==7|| state ==8;}publicstaticvoidmain(String[] args)throws InterruptedException {// String num = "-1e-16";
String num =".8";// long start = System.currentTimeMillis();// Thread.sleep(1);
System.out.println(isNumeric(num.toCharArray()));// System.out.println("执行时长:"+(System.currentTimeMillis() -// start)+" ms");}}