May be the best understand Java Solution


  • 0
    F
    public class Solution {
    public boolean isNumber(String s) {
        if (s == null || s.trim().equals("")) {
            return false;
        }
        if (s.contains("e")){
            if (s.trim().startsWith("e") || s.trim().endsWith("e")) {
                return false;
            }
            String[] ss = s.split("e");
            if (ss.length != 2) {
                return false;
            }
            return isNumber(leftTrim(ss[0].toCharArray()), true) && isNumber(rightTrim(ss[1].toCharArray()), false);
        } else {
            return isNumber(s.trim().toCharArray(), true);
        }
    }
    private boolean isNumber(char[] str, boolean acceptComma) {
        if (str.length <= 0) {
            return false;
        }
        boolean hasNumber = false;
        boolean hasComma = false;
        for (int i = 0; i < str.length; i++) {
            if ((str[i] == '-' || str[i] == '+') && i == 0) {
                continue;
            }
            if (str[i] == '.') {
                if (!acceptComma || hasComma) {
                    return false;
                } else {
                    hasComma = true;
                    continue;
                }
            }
            if (str[i] >= '0' && str[i] <= '9') {
                hasNumber = true;
                continue;
            } else {
                return false;
            }
        }
        if (!hasNumber) {
            return false;
        }
        return true;
    }
    private char[] leftTrim(char[] str) {
        if (str.length <= 0) {
            return str;
        }
        int index = 0;
        while(str[index] == ' ' && index < str.length - 1) {
            index++;
        }
        return Arrays.copyOfRange(str, index, str.length);
    }
    private char[] rightTrim(char[] str) {
        if (str.length <= 0) {
            return str;
        }
        int index = str.length - 1;
        while(str[index] == ' ' && index > 0) {
            index--;
        }
        return Arrays.copyOfRange(str, 0, index + 1);
    }
    

    }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.