java regex solution, how to improve the runtime performance? thanks

  • 0

    I'd prefer regex solution instead of writing a bunch of code to check the string char by char. but I spent sometime looking into the Java regex pattern, and submitted several times because of failed on some test case. The description of expected format is very ambiguous. And the runtime performance is kind of slow. If you could point how to improve the performance, I'd appreciate it very much.

    public boolean isNumber(String s) {
        if(s == null || s.length() == 0) {
            return false;
        s = s.trim();
        String integers = "[-+]{0,1}\\d+";
        String floats = "[-+]{0,1}\\d*\\.\\d+|[-+]{0,1}\\d+\\.\\d*";
        String iorf =  "(" + integers + '|' + floats + ")";
        String scientific = iorf + "e"+ integers;
        return s.matches(iorf) || s.matches(scientific);

Log in to reply

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