6ms in C base on Finite Automata Machine


  • 1
    S

    /**

    • 基于自动机的数字验证
    • base on Finite Automata Machine ;
      */

    bool isNumber(char *s) {

    int state = 0;
    
    while(*(s) == ' ') s++ ;
    
    if(*s == '+' || *s == '-')
        s++;
    
    if(*s == '.' && *(s + 1) == '\0')
        return false ;
    else if(*s == '.' && *(s + 1) == ' ')
        return false ;
    else if(*s == '.' && (*(s + 1) == 'E' || *(s + 1) == 'e'))
        return false ;
    
    while(*s != '\0')
    {
         switch(state){
             
            case 0 :    if(isdigit(*s)) {state = 1;  s++;}
                        else if(*s == '.') {state = 2 ; s++;}
                        else if(*s == ' ') {state = 7;s++;}
                        else goto Exit ;
                        break ;
            case 1 :    if(isdigit(*s)) {state =1; s++ ;}
                        else if (*s == '.') {state =2 ; s++;}
                        else if (*s == 'E' || *s == 'e') {state =4 ; s++;}
                        else if(*s == ' ') {state = 7;s++;}
                        else goto Exit ;
                        break;
            case 2 :    if(isdigit(*s)) {state =3 ;s++;}
                        else if (*s == 'E' || *s == 'e') {state =4 ; s++;}
                        else if(*s == ' ') {state = 7;s++;}
                        else goto Exit ;
                        break;
            case 3 :    if(isdigit(*s)) {state = 3 ; s++;}
                        else if(*s == 'E' || *s == 'e') {state =4 ; s++;}
                        else if(*s == ' ') {state = 7;s++;}
                        else goto Exit;
                        break;
            case 4 :    if(isdigit(*s)) {state = 6 ; s++;}
                        else if(*s == '+' || *s == '-') {state = 5; s++;}
                        else goto Exit;
                        break;
            case 5 :    if(isdigit(*s)) {state = 6 ; s++;}
                        else if(*s == ' ') {state = 7;s++;}
                        else goto Exit;
                        break;
            case 6 :    if(isdigit(*s)) {state = 6 ; s++;}
                        else if(*s == ' ') {state = 7;s++;}
                        else goto Exit;
                        break;
            case 7 :    if(*s != ' ')  goto Exit ;
                        else    s++;
                        break ;
         }  
    }
    
    if(state == 0 ||  state == 4 || state == 5 )
        return false ;
    
    return true;
    
    Exit : return false ;
    

    }


Log in to reply
 

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