A clean code with FSM


  • 4
    L
    bool isNumber(string s) {
        int fsm[12][256];
        memset(fsm,-1,sizeof(fsm));
        fsm[0]['.']=fsm[1]['.']=fsm[2]['.']=4;
        fsm[0]['+']=fsm[0]['-']=fsm[1]['+']=fsm[1]['-']=2;
        fsm[0][' ']=fsm[1][' ']=1;
        fsm[3]['.']=fsm[6]['.']=7;
        fsm[3]['e']=fsm[3]['E']=fsm[6]['e']=fsm[6]['E']=fsm[7]['e']=fsm[7]['E']=fsm[9]['e']=fsm[9]['E']=8;
        fsm[3][' ']=fsm[5][' ']=fsm[6][' ']=fsm[7][' ']=fsm[9][' ']=fsm[11][' ']=5;
        fsm[8]['+']=fsm[8]['-']=10;
        for(char d='0';d<='9';++d){
            fsm[0][d]=fsm[1][d]=fsm[2][d]=3;
            fsm[3][d]=fsm[6][d]=6;
            fsm[4][d]=fsm[7][d]=fsm[9][d]=9;
            fsm[8][d]=fsm[10][d]=fsm[11][d]=11;
        }
        int state=0;
        for(int i=0,len=s.length();i<len;++i){
            state=fsm[state][s[i]];
            if(state==-1) break;
        }
        return state==3 || state==5 || state==6 || state==7 || state==9 || state==11;
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.