AC Java solution with clear explanation


  • 19
    public class Solution {
        public boolean isNumber(String s) {
            if (s == null) return false;
            
            s = s.trim();
            int n = s.length();
            
            if (n == 0) return false;
            
            // flags
            int signCount = 0;
            boolean hasE = false;
            boolean hasNum = false;
            boolean hasPoint = false;
            
            for (int i = 0; i < n; i++) {
                char c = s.charAt(i);
                
                // invalid character
                if (!isValid(c)) return false;
                
                // digit is always fine
                if (c >= '0' && c <= '9') hasNum = true;
                
                // e or E
                if (c == 'e' || c == 'E') {
                    // e cannot appear twice and digits must be in front of it
                    if (hasE || !hasNum) return false;
                    // e cannot be the last one
                    if (i == n - 1) return false;
                    
                    hasE = true;
                }
                
                // decimal place
                if (c == '.') {
                    // . cannot appear twice and it cannot appear after e
                    if (hasPoint || hasE) return false;
                    // if . is the last one, digits must be in front of it, e.g. "7."
                    if (i == n - 1 && !hasNum) return false;
                    
                    hasPoint = true;
                }
                
                // signs
                if (c == '+' || c == '-') {
                    // no more than 2 signs
                    if (signCount == 2) return false;
                    // sign cannot be the last one
                    if (i == n - 1) return false;
                    // sign can appear in the middle only when e appears in front
                    if (i > 0 && !hasE) return false;
                    
                    signCount++;
                }
            }
            
            return true;
        }
        
        boolean isValid(char c) {
            return c == '.' || c == '+' || c == '-' || c == 'e' || c == 'E' || c >= '0' && c <= '9';
        }
    }

  • 0
    S

    Thank you for your prompt


  • 0
    H

    I think this is a real answer.
    voted like

    but "3e88+9" is a invalid number which is regarded as valid in this solution.

    Add another condition that when "+/-" appears it's either the first one or with an "e/E" inbefore


Log in to reply
 

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