Java for LeetCode 065 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.

解题思路:

本题边界条件颇多"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;
					else
						return false;
				} else
					return false;
			}
		}
		return true;
	}
原文地址:https://www.cnblogs.com/tonyluis/p/4507515.html