標籤:
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.
解題思路:
本題邊界條件頗多"1.", ".34","1.1e+.1"也是正確的。解題方法是先trim一下,然後按照e進行劃分,然後分別對e前後進行判斷JAVA實現如下:
public boolean isNumber(String s) {s = s.trim();String[] splitArr = s.split("e");if (s.length() == 0 || s.charAt(0) == ‘e‘|| s.charAt(s.length() - 1) == ‘e‘ || splitArr.length > 2)return false;for (int k = 0; k < splitArr.length; k++) {String str = splitArr[k];boolean isDecimal = false;if (str.charAt(0) == ‘-‘ || str.charAt(0) == ‘+‘)str = str.substring(1);if (str.length() == 0)return false;for (int i = 0; i < str.length(); i++) {if (‘0‘ <= str.charAt(i) && str.charAt(i) <= ‘9‘)continue;else if (str.charAt(i) == ‘.‘ && !isDecimal) {if (k == 0 && str.length() > 1)isDecimal = true;elsereturn false;} elsereturn false;}}return true;}
Java for LeetCode 065 Valid Number