题目链接: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 ValidNumber {
// 1481 / 1481 test cases passed.
// Status: Accepted
// Runtime: 214 ms
// Submitted: 0 minutes ago
//时间复杂度O(n) 空间复杂度O(1)
public boolean isNumber(String s) {
int i = 0;
s = s.trim(); // 去除两端的空格
boolean hasDecimal = false; // 标记是否已经出现了 小数点(.)
boolean hasNum = false; // 标记之前的字符串是否是数值了
boolean hasE = false; // 标记是否已经出现了 (e)字符
if (s.length() == 0)
return false;
// 判断是否有正负号字符
if (isSign(s.charAt(0))) {
i++;
}
while (i < s.length()) {
char c = s.charAt(i);
if (isDigit(c)) {
if (!hasNum) {
hasNum = true;
}
} else if (isDecimal(c)) {
if (hasDecimal || hasE) // 整个数值只能出现一个小数点(.); e的指数不能为小数;
return false;
hasDecimal = true;
} else if (isE(c)) {
// 如果之前的字符已经出现(e)字符,或者(e)出现在整个字符的最前或最后,则都不是一个有效的数值
if (hasE || !hasNum || (++i) >= s.length())
return false;
// 判断指数是否有符号位
if (!isSign(s.charAt(i)))
i--;
hasE = true;
hasNum = false; // 需要重新寻找一个数值
} else
return false; // 如果有 (数字、小数点.、字符e)以外的字符
i++;
}
return hasNum;
}
public boolean isSign(char c) {
return c == '+' || c == '-';
}
public boolean isDigit(char c) {
return (c - '0' >= 0 && c - '0' <= 9);
}
public boolean isDecimal(char c) {
return c == '.';
}
public boolean isE(char c) {
return c == 'e';
}
public static void main(String[] args) {
System.out.println(new ValidNumber().isNumber("0"));
System.out.println(new ValidNumber().isNumber(" 0.1 "));
System.out.println(new ValidNumber().isNumber("abc"));
System.out.println(new ValidNumber().isNumber("1 a"));
System.out.println(new ValidNumber().isNumber("2e10"));
System.out.println(new ValidNumber().isNumber(".1"));
System.out.println(new ValidNumber().isNumber("6e6.5"));
}
}