My java 3ms solution with state change


  • 0
    K
    public boolean isNumber(String s) {
                    final int EMPTY = 0;
    		final int NUMBER = 1;
    		final int DOT_NUMBER = 2;
    		final int NUMBER_DOT = 3;
    		final int ONLY_E = 4;
    		final int E_NUMBER = 5;
    		final int ONLY_DOT = 6;
    		final int E_POWER = 7;
    		int preState = EMPTY ; // pre state
    		char[] charArr = s.trim().toCharArray();
    		int length = charArr.length;
    		int e = 'e';
    		int dot = '.';
    		int neg = '-';
    		int pos = '+';
    		for(int index = 0 ; index < length;index++ ){
    			char cur = charArr[index];
    			if(cur == e ){
    				if (preState == NUMBER_DOT || preState == NUMBER || preState == DOT_NUMBER) {
    					preState = ONLY_E;
    				}else {
    					return false;
    				}
    			}else if(cur == dot){
    				if (preState == EMPTY) {
    					preState = ONLY_DOT;
    				}else if(preState == NUMBER ){
    					preState = NUMBER_DOT;
    				}else {
    					return false;
    				}
    			}else if(cur >= 48 && cur <= 57){
    				if (preState == EMPTY ) {
    					preState = NUMBER;
    				}
    				if (preState == ONLY_E || preState == E_NUMBER || preState == E_POWER) {
    					preState = E_NUMBER;
    				}
    				if (preState == ONLY_DOT || preState == DOT_NUMBER || preState == NUMBER_DOT) {
    					preState = DOT_NUMBER;
    				}
    			}else if(cur == neg || cur == pos){
    				if (preState == ONLY_E) {
    					preState = E_POWER;
    				}else if(preState != EMPTY){
    					return false;
    				}
    			}else {
    				return false;
    			}
    		}
    		
    		if(preState ==E_NUMBER || preState == NUMBER || preState == NUMBER_DOT || preState == DOT_NUMBER){
    			return true;
    		}
    		return false;
        }
    

Log in to reply
 

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