State Pattern or FSM help this out


  • 0
    
    	enum State {
    		INTEGER, DOUBLE, EXP
    	}
    
    	public boolean isNumber(String s) {
    		s = s.trim();
    		if (s.isEmpty())
    			return false;
    		char[] sa = s.toCharArray();
    		State state = State.INTEGER;
    		boolean startOfState = true;
    		for (int i = 0; i < sa.length; i++) {
    			if (sa[i] == '-' || sa[i] == '+') {
    				if (!startOfState || state == State.DOUBLE) {
    					return false;
    				}
    			} else if (Character.isDigit(sa[i])) {
    				startOfState = false;
    				continue;
    			} else if (sa[i] == '.') {
    				if (state == State.DOUBLE || state == State.EXP)
    					return false;
    				state = State.DOUBLE;
    			} else if (sa[i] == 'e') {
    				if (startOfState || state == State.EXP)
    					return false;
    				startOfState = true;
    				state = State.EXP;
    			} else {
    				return false;
    			}
    		}
    		return !startOfState;
    	}
    }
    

Log in to reply
 

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