Java solution. I kind of dislike this problem.


  • 0
    Y
       /*
        *  summary type
        *  space  [+/-]  number(or point number) option: e [+/-] number space.
        *
        * */
        private boolean isDigit(int index, String s) {
            if (index < 0 || index >= s.length()) return false;
            return Character.isDigit(s.charAt(index));
        }
    
        private boolean isOP(int index, String s) {
            if (index < 0 || index >= s.length()) return false;
            return s.charAt(index) == '+' || s.charAt(index) == '-';
        }
    
        private boolean isDot(int index, String s) {
            if (index < 0 || index >= s.length()) return false;
            return s.charAt(index) == '.';
        }
    
        public boolean isNumber(String s) {
            if (0 == s.length()) return false;
    
            int i = 0;
            int n = s.length();
    
            // remove leading space
            while (i < n && ' ' == s.charAt(i)) ++i;
            if (i == n) return false;
    
            int indexOfDot = -1, indexOfE = -1;
            boolean spaceExisted = false;
    
            while (i < n) {
                char c = s.charAt(i);
                if (spaceExisted && c != ' ') return false;
    
                if ('.' == c) {   // .      +. is also valid.
                    if (indexOfDot != -1) return false;
                    if (!isDigit(i - 1, s) && !isDigit(i + 1, s) && !isOP(i + 1, s)) return false;
                    if (-1 != indexOfE) return false;
    
                    indexOfDot = i;
                }
                else if ('e' == c) {   //e [+/1] number  there must be something behind and ahead of e
                    if (indexOfE != -1 || i == n - 1 || i - 1 < 0 
                            || s.charAt(i - 1) == ' '|| s.charAt(i + 1) == ' ')  return false;
                    indexOfE = i;
                }
                else if ('+' == c || '-' == c) { // must be the form +/- [.] number...
                    if (i - 1 >= 0 && s.charAt(i - 1) != ' ' && s.charAt(i - 1) != 'e') return false;
                    if (!isDigit(i + 1, s) && !isDot(i + 1, s)) return false;   
                }
                else if (' ' == c) spaceExisted = true; // the rest must be also space
                else if (!isDigit(i, s)) return false;
    
                ++i;
            }
    
            return true;
        }
    
    

Log in to reply
 

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