Java solution, a little long, but easy to understand, with state machine


  • 0
    L
    public class Solution {
        public boolean isNumber(String s) {
            char[] sr = s.trim().toCharArray();
            State state = State.START, lastState = state;
            for (int i = 0; i < sr.length; i++) {
                switch (state) {
                    case START:
                        if (sr[i] == '.') state = State.DECI;
                        else if (sr[i] >= '0' && sr[i] <= '9') state = State.INTE;
                        else if (sr[i] == '+' || sr[i] == '-') state = State.SIGN;
                        else return false;
                        break;
                    case INTE:
                        if (sr[i] == '.') { state = State.DECI; lastState = State.INTE; }
                        else if (sr[i] == 'e') state = State.EXP;
                        else if (!(sr[i] >= '0' && sr[i] <= '9')) return false;
                        break;
                    case SIGN:
                        if (sr[i] == '.') state = State.DECI;
                        else if (sr[i] >= '0' && sr[i] <= '9') state = State.INTE;
                        else return false;
                        break;
                    case DECI:
                        if (sr[i] >= '0' && sr[i] <= '9') state = State.DECIINTE;
                        else if (lastState == State.INTE && sr[i] == 'e') state = State.EXP;
                        else return false;
                        break;
                    case DECIINTE:
                        if (sr[i] == 'e') state = State.EXP;
                        else if (!(sr[i] >= '0' && sr[i] <= '9')) return false;
                        break;
                    case EXP:
                        if (sr[i] >= '0' && sr[i] <= '9') state = State.EXPINTE;
                        else if (sr[i] == '+' || sr[i] == '-') state = State.EXPSIGN;
                        else return false;
                        break;
                    case EXPINTE:
                        if (!(sr[i] >= '0' && sr[i] <= '9')) return false;
                        break;
                    case EXPSIGN:
                        if (sr[i] >= '0' && sr[i] <= '9') state = State.EXPINTE;
                        else return false;
                        break;
                }
            }
            
            if ((state == State.DECI && lastState == State.INTE) || 
                state == State.DECIINTE || state == State.EXPINTE || state == State.INTE) return true;
            return false;
        }
        private enum State {START, SIGN, INTE, DECI, DECIINTE, EXP, EXPSIGN, EXPINTE};
    }

Log in to reply
 

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