My java answer,without regex ,without parsing to number, one pass.


  • 1
    C
    public boolean isNumber(String s) {
        String ss=s.trim();
        int state=1; boolean canSymbolAppear=true; boolean valid=false; boolean canPointAppear=true;
        for(int i=0;i<ss.length();i++){
            char c=ss.charAt(i);
            if((c=='+' || c=='-') && canSymbolAppear ) {
                canSymbolAppear=false;
                continue;
            }
            switch(state){
             case 1:
                 if(isDigit(c)) {
                     valid=true;
                     canSymbolAppear=false;
                     continue;
                 }
                 else if(isPoint(c) && canPointAppear) {
                     canPointAppear=false;
                     canSymbolAppear=false;
                     continue;
                 }
                 else if(isE(c) && valid){
                     state=2;
                     canSymbolAppear=true;
                     valid=false;
                     continue;
                 }
                 else return false;
    
            case 2:
                 if(isDigit(c)) {
                     valid=true;
                     canSymbolAppear=false;
                     continue;
                 }
                 else return false;
            default: return false;
            }
            
        }
        if(valid) return true;
        else return false;
     
    }
    public boolean isDigit(char s){
        return (s>='0' && s<='9');
    }
    public boolean isPoint(char s){
        return s=='.';
    }
    public boolean isE(char s){
        return (s=='e' || s=='E');
    }

  • 0
    C

    state 1 : the state if 'e' doesn't appear.

    state 2 : the state if 'e' did appear.

    canSymbolAppear : whether '+' or '-' can appear at this moment

    canPointAppear: whether '.' can appear at this moment.

    valid : whether it is valid state at this moment


Log in to reply
 

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