Thursday, January 8, 2015

LeetCode 65: Valid Number

Validate if a given string is numeric.
Some examples:
"0" => true
" 0.1 " => true
"abc" => false
"1 a" => false
"2e10" => true

Note: It is intended for the problem statement to be ambiguous. You should gather all requirements up front before implementing one.
public class Solution {
    public boolean isNumber(String s) {
        // Similar to question "String to Integer (atoi)", we should consider multiple special cases.
        // Case 1. There may be 'e' between the numbers, but it can only appear once.
        // Case 2. '.' can't appear after 'e' and it can only appear once.
        // Case 3. '+' and '-' can only appear at the first position of number or follow 'e'.
        int n = s.length();
        
        if (n == 0)
            return false;
            
        // Cut the leading spaces and tail spaces.
        String sCut = s.trim();
        
        n = sCut.length();
        
        boolean num = false; // If digits appear or not
        boolean exp = false;
        boolean dot = false;
        
        for (int i = 0; i < n; i++)
        {
            char c = sCut.charAt(i);
            
            // Case 1
            if (c == 'e')
            {
                // If digits didn't appear or 'e' has already appeared, return false.
                if (!num || exp)
                    return false;
                    
                // Should be: "2e2", so there should be digits after 'e'; Otherwise, still finally return false.
                num = false;                    
                    
                exp = true;
            }
            else if (c>='0' && c<='9')
                num = true;
            // Case 2
            else if (c == '.')
            {
                // If 'e' or '.' has already appeared, return false.
                // Can't be: "e0.2"; Can't be: "..".
                if (exp || dot)
                    return false;
                
                dot = true;
            }
            // Case 3
            else if (c=='+' || c=='-')
            {
                // "-005047e+6" is true.
                if (i != 0 && sCut.charAt(i-1) != 'e')
                    return false;
            }
            else
                // Invalid character.
                return false;
        }
        
        return num;
    }
}

No comments:

Post a Comment