Valid Number
Solution: use a pointer to scan through the string. The pointer only could be moved under valid conditions.
In the end, check if we scan through the entire string to determine whether the string is a valid number.
public boolean isNumber(String s) {
// return false if the length of string is 0
if (s == null || s.length() == 0) return false;
// remove leading and trailing white space
s = s.trim();
// use a poitner i to scan thrgouh the string
// we can set up some conditions to make sure the move of i is always valid,
// if after the scanning, i equals to n, it means this string is a valid number.
int i = 0, n = s.length();
if (i < n && (s.charAt(i) == '+' || s.charAt(i) == '-'))
i++;
boolean isNumeric = false;
while (i < n && Character.isDigit(s.charAt(i))) {
isNumeric = true;
i++;
}
// handle two special cases: '.' and 'e' (decimal and exponent numbers)
// when we encounter decimal number
if (i < n && s.charAt(i) == '.') {
i++;
while (i < n && Character.isDigit(s.charAt(i))) {
isNumeric = true;
i++;
}
}
// when we encounter exponent number
// there must be number occur before and after 'e'
if (i < n && s.charAt(i) == 'e' && isNumeric) {
i++;
// plus sign and minus sign after 'e'
isNumeric = false;
if (i < n && (s.charAt(i) == '+' || s.charAt(i) == '-'))
i++;
while (i < n && Character.isDigit(s.charAt(i))) {
isNumeric = true;
i++;
}
}
return isNumeric && i == n;
}