Validate parentheses in an input String.

The interview test validates that the parentheses in an input String a marching.

If the parentheses match, the method returns true, otherwise it returns false.

This method counts the number matching parentheses. If at the end of the input the count is not 0, or at any moment the count is less than 0, then the parentheses are not matching an the method returns false.

Create the following java file:

public class InterviewValidateParentheses {

    public boolean isValid(String input) {
        if (input == null)
            return true;

        int opened = 0;
        for (int i = 0; i < input.length(); i++) {
            char c = input.charAt(i);

            if (c == '(') {
                opened++;
            } else if (c == ')') {
                opened--;
                if (opened < 0) {
                    return false;
                }
            }
        }

        if (opened == 0)
            return true;

        return false;
    }

    public static void main(String[] argv) throws Exception {
        InterviewValidateParentheses t = new InterviewValidateParentheses();

        System.out.println("Valid=" + t.isValid("(abc)"));
        System.out.println("Valid=" + t.isValid("((abc)"));
        System.out.println("Valid=" + t.isValid("(abc))"));
        System.out.println("Valid=" + t.isValid("(()(abc)"));
    }

}

The output will be:

Valid=true
Valid=false
Valid=false
Valid=false

The method is validated using 4 examples: too many outside opening parentheses, too many outside closing parenthese and the same with inside parentheses.

References:

Parenthesis Matching

Share this article:

Recent Comments