Friday, June 9, 2017

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.
Update (2015-02-10):
The signature of the C++ function had been updated. If you still see your function signature accepts a const char * argument, please click the reload button  to reset your code definition.



Solution:

First trim the whitespace from two sides.

Then we maintain three booleans:

num: its a digit

dot: its a '.'

exp: its a 'e'

Go through the remaining string and check if the current character will change the status of these three variables.



Code:


public class Solution {
    public boolean isNumber(String s) {
        int len = s.length();
        int i = 0;
        int j = len - 1;
        while (i <= j && s.charAt(i) == ' ') {
            i++;
        }
        if (i > j) {
            return false;
        }
        while (i <= j && s.charAt(j) == ' ') {
            j--;
        }
        if (s.charAt(i) == '+' || s.charAt(i) == '-') {
            i++;
        }
        boolean num = false;
        boolean dot = false;
        boolean exp = false;
        while (i <= j) {
            char c = s.charAt(i);
            if (c >= '0' && c <= '9') {
                num = true;
            }
            else if (c == '.') {
                if (dot || exp) {
                    return false;
                }
                dot = true;
            }
            else if (c == 'e') {
                if (exp || !num) {
                    return false;
                }
                exp = true;
                num = false;
            }
            else if (c == '+' || c == '-') {
                if (s.charAt(i - 1) != 'e') {
                    return false;
                }
            }
            else {
                return false;
            }
            i++;
        }
        return num;
    }
}



Method 2: DFA

Detailed explanation:

Link 1: English, python

Link 2: Chinese, Java


Code: