LeetCode | Valid Number

2014-11-24 10:42:35 · 作者: · 浏览: 0

题目

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:利用正则表达式。

解法2:直接利用java提供的parseDouble或parseFloat函数帮助判断,这算是投机取巧的方法了,需要注意的是java类库里认为以“f”, "F", "d", "D"结尾的都是合法的,而LeetCode上都视为非法,需要特殊处理下。parseDouble和parseFloat具体的实现方法都是用的类库中的FloatingDecimal.readJavaFormatString(s),源码参见http://www.bvbcode.com/cn/joa60xtr-137004。

解法1

public class ValidNumber {
	public boolean isNumber(String s) {
		return s.trim().matches("[-+] (\\d+\\. |\\.\\d+)\\d*(e[-+] \\d+) ");
	}
}
解法2

public class ValidNumber {
	public boolean isNumber(String s) {
		if (s.contains("f") || s.contains("f") || s.contains("d")
				|| s.contains("D")) {
			return false;
		}
		try {
			Double.parseDouble(s);
		} catch (Exception e) {
			return false;
		}
		return true;
	}
}