apachecn / apachecn-algo-zh

ApacheCN 数据结构与算法译文集
https://algo.apachecn.org/
11.03k stars 2.19k forks source link

using another method to solve question 20 #185

Closed mcrwayfun closed 5 years ago

mcrwayfun commented 5 years ago

使用剑指offer上的思路来解决第20题,代码如下:

public class Solution {

    private int index = 0;

    /**
     * 判断是否是数值
     * @param  str 
     * @return 
     */
    public boolean isNumeric(char[] str) {
        if (str.length < 1)
            return false;

        boolean flag = scanInteger(str);

        if (index < str.length && str[index] == '.') {
            index++;
            flag = scanUnsignedInteger(str) || flag;
        }

        if (index < str.length && (str[index] == 'E' || str[index] == 'e')) {
            index++;
            flag = flag && scanInteger(str);
        }

        return flag && index == str.length;

    }

    private boolean scanInteger(char[] str) {
        if (index < str.length && (str[index] == '+' || str[index] == '-'))
            index++;
        return scanUnsignedInteger(str);

    }

    private boolean scanUnsignedInteger(char[] str) {
        int start = index;
        while (index < str.length && str[index] >= '0' && str[index] <= '9')
            index++;
        // 是否存在整数
        return start < index;
    }
}