My code:
public class Solution {
public boolean isNumber(String s) {
int i = 0;
int e = s.length() - 1;
while (i <= e && s.charAt(i) == ' ') {
i++;
}
if (i > e) {
return false;
}
while (e >= i && s.charAt(e) == ' ') {
e--;
}
if (s.charAt(i) == '+' || s.charAt(i) == '-') {
i++;
}
boolean num = false;
boolean dot = false;
boolean exp = false;
while (i <= e) {
char curr = s.charAt(i);
if (Character.isDigit(curr)) {
num = true;
}
else if (curr == '.') {
if (exp || dot) {
return false;
}
dot = true;
}
else if (curr == 'e') {
if (exp || !num) {
return false;
}
exp = true;
num = false;
}
else if (curr == '+' || curr == '-') {
if (s.charAt(i - 1) != 'e') {
return false;
}
}
else {
return false;
}
i++;
}
return num;
}
}
reference:
http://www.jiuzhang.com/solutions/valid-number/
这种题,其实一点意义都没。连 valid number 的定义都没。
死记下最简单的答案吧。
Anyway, Good luck, Richardo! — 10/15/2016