Wednesday, August 21, 2013

[Leetcode]: 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. 整型 - [+-]?\\d+
2. 浮点数 - 小数点至少一旁为整型
3. 含e的表达式 - e的左边为浮点数,右边为整型

  
public class Solution {
    public boolean isNumber(String s) {
        String number_re = "\\s*[+-]?(\\d+\\.?\\d*|\\d*\\.\\d+)(e[+-]?\\d+)?\\s*";
        return s.matches(number_re);
    }
}
这题的关键就是要考虑到各个coners。

1 comment: