Accepted java solution with recursion


  • 6
    Z

    I know I should describe the logic but I think it's quite readable. It recursively checks parts of the input string.

    It first checks whether it contains an 'e': if yes, then left side should be a float or an integer and right side should be an integer. If no 'e' was found then whole string should be a float or an integer. And so on...

    public boolean isNumber(String str) {
        if (str == null) {
            return false;
        }
        str = str.trim();
        if (str.isEmpty()) {
            return false;
        }
        int index;
        if ((index=str.indexOf('e')) != -1) {
            return isFloatOrInteger(str, 0, index-1) && 
                   isInteger(str, index+1, str.length()-1);
        } else {
            return isFloatOrInteger(str, 0, str.length()-1);
        }
    }
    
    private boolean isInteger(String str, int from, int to) {
        if (from > to) {
            return false;
        }
        if (str.startsWith("+", from) || str.startsWith("-", from)) {
            return isUnsignedInteger(str, from+1, to);
        } else {
            return isUnsignedInteger(str, from, to);
        }
    }
    
    private boolean isUnsignedInteger(String str, int from, int to) {
        if (from > to) {
            return false;
        }
        for (int i=from; i<=to; i++) {
            if (str.charAt(i) < '0' || str.charAt(i) > '9') {
                return false;
            }
        }
        return true;
    }
    
    private boolean isFloatOrInteger(String str, int from, int to) {
        if (from > to) {
            return false;
        }
        if (str.startsWith("+", from) || str.startsWith("-", from)) {
            return isUnsignedFloatOrInteger(str, from+1, to);    
        } else {
            return isUnsignedFloatOrInteger(str, from, to);    
        }
    }
    
    private boolean isUnsignedFloatOrInteger(String str, int from, int to) {
        if (from > to) {
            return false;
        }
        int index = str.indexOf('.', from);
        if (index > -1 && index <= to) {
            return (from != index || to != index) && 
                   (isUnsignedInteger(str, from, index-1) || from == index) && 
                   (isUnsignedInteger(str, index+1, to) || index == to);
        } else {
            return isUnsignedInteger(str, from, to);
        }
    }

Log in to reply
 

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