[LintCode] Valid Number

473 查看

Problem

Validate if a given string is numeric.

Example

"0" => true

" 0.1 " => true

"abc" => false

"1 a" => false

"2e10" => true

Note

if !e
A can be '+/-' + int + '.' + int

if e: AeB
A can be '+/-' + int + '.' + int
B can be '+/-' + int

两种情况:有无e,如上所示。
然后按有无e来拆分字符串,若拆分之后只有一部分,即用helper()函数判断是否满足构成数的规则;若有两部分,则对前一部分按数A(可以有小数部分)分析,后一部分按构成数B分析(只能为整数)。
如何判断是否只有一个esplit()之后的String[]长度小于等于2。
由于数A和数B的区别只存在于有没有小数点'.',建立一个flag hasDot(),其他应用一样的规则即可。注意,s为空、只有"e"、"e"在字符串最末位、或者只有"."都是错误的。

规则:若字符串首位为+/-,取其.substring(1),然后将string应用toCharArray()转换为char数组,逐位判断字符,出现'.'将hasDot()true;如hasDot()已经置true,再次出现'.'则直接返回false。然后判断其余位是否为数字即可。

Solution

public class Solution {

public boolean isNumber(String s) {
    s = s.trim();
    if (s == null || (s.length() > 0 && s.charAt(s.length()-1) == 'e') || s.equals(".")) return false;
    String[] strs = s.split("e");
    if (strs.length > 2) return false;
    boolean res = helper(strs[0], false);
    if (strs.length == 2) {
        res = res && helper(strs[1], true);
    }
    return res;
}
public boolean helper(String s, boolean hasDot) {
    if (s.length() > 0 && (s.charAt(0) == '+' || s.charAt(0) == '-'))
        s = s.substring(1);
        char[] ch = s.toCharArray();
        if (ch.length == 0) return false;
        for (int i =  0; i < ch.length; i++) {
            if (ch[i] == '.') {
                if (hasDot) return false;
                hasDot = true;
            }
            else if (!(ch[i] >= '0' && ch[i] <= '9')) return false;
        }
        return true;
}

}