Can this While loop be simplified?

Viewed 224

Consider the following code. It is for check if the String has valid parenthesis but without using stack.

public boolean isValid(String input) {
       
    while(input.length() != (input = input.replaceAll("\\(\\)|\\[\\]|\\{\\}", "")).length());
    return input.isEmpty();
}

But Kinda difficult to understand. Can this be simplified? Without adding more number of new lines?

3 Answers

It helps if you first format and indent it properly:

public boolean isValid_2(String input) {
    while(input.length() != (input = input.replaceAll("\\(\\)|\\[\\]|\\{\\}", "")).length())
        ;
    return input.isEmpty();
}

Next, notice that the method doesn't depend on instances of its class, so can be static. Also, remove redundant escapes from the regex:

public static boolean isValid_3(String input) {
    while(input.length() != (input = input.replaceAll("\\(\\)|\\[]|\\{}", "")).length())
        ;
    return input.isEmpty();
}

Finally, break up the complicated statement into easy-to-understand parts, and introduce some variables with meaningful names, and then change the type of loop to something more useful, and you have your final version:

public static boolean isValid_4(String input) {
    int oldLength, newLength;
    do {
        oldLength = input.length();
        input = input.replaceAll("\\(\\)|\\[]|\\{}", "");
        newLength = input.length();
    } while (oldLength != newLength);
    return input.isEmpty();
}

My simplification is this:

static boolean isValid(String input) {
    String t = input, s;
    do {
        s = t;
        t = s.replaceAll("\\(\\)|\\[\\]|\\{\\}", "");
    } while (s.length() != t.length());
    return t.isEmpty();
}   

which, though longer, makes it easier IMO to see what's going on. I like brevity, but it's not always best.

This differs from other simplification answers in that it focuses more on the remaining strings than on the lengths, which to my mind is more to the point. But at some point, this is a matter of aesthetics.

(Also, you can conveniently stick a "print" after the assignments in the loop, to see what is really happening - I did this to debug my incorrect comment)

Note: The question has been updated after I've answered the question. So, if doesn't fulfill the questions answer's each and every aspect, then please just ignore it.

let's see:

public boolean isValid(String input) {
    
    int prevLength = input.length();

    input = input.replaceAll("\\(\\)|\\[\\]|\\{\\}", "");
    
    while(prevLength != input.length()) {
        prevLength = input.length();
        input = input.replaceAll("\\(\\)|\\[\\]|\\{\\}", "");
    }
    
    return input.isEmpty();
}

I guess its enough simplified...

Related