Leetcode #65 Valid Number

Leetcode #65 Valid Number

Difficulty: Hard

ยท

2 min read

Ok. To be honest, this is a really sloppy answer and a poor attempt from me with this question.

My initial thought was "Ok, regex should work". But obviously, this question is hard, only 16% acceptance rate. So towards the end, I basically "brute force" it and kept adding "valid/invalid" regexes to just try and make it work.

I will probably try this question for a more elegant solution another day. But if this question did come up in any of my interviews, I don't think I can produce a solution within the 45-minute time frame. ๐Ÿ˜…

This regex basically checks if the integer is valid. I probably don't quite know what I wrote for the rest of them, since I kept adding valid combination as I go.

Anyway, this quote is so true when I try to solve this question. ๐Ÿ˜‚

I have 1 problem. But when I try to use Regex to solve the problem. I have 2 problems.

Eg: (.\d+e\d+) : .234e3 , (\d+.+e+\d+) : 165.e345

/^(+|-)?\d+$/g

Regex Playground Link: Regex101

Link: Valid Number

First Attempt (After 8 submissions ๐Ÿ˜ต)

/**
 * @param {string} s
 * @return {boolean}
 */
var isNumber = function(s) {
    // 3 regex for valid number, decimal, int
    let isValid = false;
    s=s.toLowerCase();
    // Valid regex
    let validNumRegex = /^(\d+)?(\+\d+|\-\d+)?(\d+)?(?:(\d+E|\d+e)?)?((\+|\-|\-\d+|\+\d+)?)?(\d+)?(?:(\d+E|\d+E\-|\d+E\+|\d+e|\d+e\-|\d+e\+))(\d+)$/g;
    let intRegex = /^(\+|\-)?\d+$/g;
    let decimalRegex = /^(\+|\-)?(\d+|\d+)?(\.\d+|\d+\.|\d+\.e\d+|\d+\.E\d+|\.\d+E\d+|\.\d+e\d+|\.\d+e\-\d+)?(\d+\.+e\-\d+|\d+\.+e\+\d+|\.\d+e\+\d+|\.\d+e\-\d+)?(\d+)?$/g
    let invalidRegex = /^(\d+e\d+e\d+)?(\+|\-|\.)?$/g;

    if(s.match(invalidRegex)){
        return false;
    }

    // Int regex
    if(s.match(intRegex)){
        return true;
    }


    // Decimal regex
    if(s.match(decimalRegex)){
        return true;
    }

    // Valid number
    if(s.match(validNumRegex) ){
        return true;
    }

    return isValid;
};

Second Attempt (Some other day)

Going to try this question with a more elegant solution some other day.

Test cases that I used

"." "-" "+" "32.e-80123" "34e.e" "92e1740e91" ".3+e" "+e.e" "35-.e" "e+e" "e+.3" "+3.e" ".5e+2" ".+5e2" ".5-2" ".+5e2" "-.3e6" ".." "ee" "3.e" "e.3" "+.-" "46.e4" "46e.4" "e" "." "6+1" "-6+1" "+6e-1" "e." "2" "0089" "-0.1" ".e4" "+e.4" "+3.14" "4." "-.9" "2e10" "-90E3" "3e+7" "53.5e93" "-123.456e789" "abc" "1a" "1e" "." "e3" "99e2.5" "--6" "-+3" "95a54e53"

Did you find this article valuable?

Support MichelleTanPY's Dev journal by becoming a sponsor. Any amount is appreciated!

ย