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.

Update (2015-02-10):
The signature of the C++ function had been updated. If you still see your function signature accepts a const char * argument, please click the reload button  to reset your code definition.

原问题链接:https://leetcode.com/problems/valid-number/

问题分析

  这个问题的复杂在于它本身要处理和判断的条件非常多,我们需要把这些所有的都整理出来。针对所有的情况来说,来列一下:

首先,在这里一个合法的数字字符串可以两边包含有空格,所以这是第一步需要处理的情况。

其次,这里的数字可能有符号,包括正,负符号,所以这是接着要判断处理的。

接着就是对于数字来说它可能是小数或者整数。对于整数来说,我们只需要记录里面出现数字的个数以及当前的索引。对于小数来说,还需要判断当前的元素是否为小数点。

这里还有一种情况,就是指数形式的表示,这里需要判断里面是否有字符e。当有这个字符的时候,需要接着再去判断后面包含有数字的个数不能为0个以及指数部分是否包含有符号,同时根据最后的索引是否到达字符串的末尾来判断。

  详细的实现如下:

public class Solution {
    public boolean isNumber(String s) {
        char[] c = s.trim().toCharArray();

        if (c.length == 0) return false;
    
        int i = 0, num = 0;
        if (c[i] == '+' || c[i] == '-') i++;
    
        for(; i < c.length && (c[i] >= '0' && c[i] <= '9'); i++) num++;
        if (i < c.length && c[i] == '.') i++;
        for(; i < c.length && (c[i] >= '0' && c[i] <= '9'); i++) num++;
    
        if(num == 0) return false;
    
        if(i == c.length) return true;
        else if(i < c.length && c[i] != 'e') return false;
        else i++;
    
        num = 0;
        if(i < c.length && (c[i] == '+' || c[i] == '-')) i++;
    
        for(; i < c.length && (c[i] >= '0' && c[i] <= '9'); i++) num++;
        if (num == 0) return false;
    
        if(i == c.length) return true;
        else return false;
    }
}

猜你喜欢

转载自shmilyaw-hotmail-com.iteye.com/blog/2302025