Validate Bracket and Parenthesis Combos Using Stacks

Valid Bracket and Parenthesis Combos are those pairs that have opening and corresponding closing brackets in the correct order.

For example () is a valid Bracket and Parenthesis pair, because opening and corresponding closing brackets are in the correct order.

)()()) is not a valid Bracket and Parenthesis pair, because first ) doesn't have corresponding closing brackets.

({[({}())]}) is a valid Bracket and Parenthesis pair, because opening and corresponding closing brackets are in the correct order.

package org.wesome.dsalgo;

import java.util.Stack;

public class ValidateBracketCombos {
    public static boolean validateBracketCombos(String brackets) {
        boolean result = true;
        Stack<Character> stack = new Stack<>();
        char current, previous;
        for (int i = 0; i < brackets.length(); i++) {
            current = brackets.charAt(i);
            if (current == '(' || current == '[' || current == '{') {
                stack.push(current);
            } else if (current == ')' || current == ']' || current == '}') {
                if (stack.isEmpty()) {
                    result = false;
                } else {
                    previous = stack.peek();
                    if ((current == ')' && previous == '(') || (current == ']' && previous == '[') || (current == '}' && previous == '{')) {
                        stack.pop();
                    } else {
                        result = false;
                    }
                }
            }
        }
        if (!stack.isEmpty()) {
            result = false;
        }
        return result;
    }
}
package org.wesome.dsalgo;

import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;

public class ConsecutiveValidParenthesisTest {
    @Test
    void validateBracketCombosTest1() {
        String parenthesis = ")()())";
        Assertions.assertFalse(ValidateBracketCombos.validateBracketCombos(parenthesis));
    }

    @Test
    void validateBracketCombosTest2() {
        String parenthesis = "({[({}())]})";
        Assertions.assertTrue(ValidateBracketCombos.validateBracketCombos(parenthesis));
    }

    @Test
    void validateBracketCombosTest3() {
        String parenthesis = "({[({}())]})({[({}())]})";
        Assertions.assertTrue(ValidateBracketCombos.validateBracketCombos(parenthesis));
    }
}
plugins {
    id 'java'
}

group = 'org.wesome'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = JavaVersion.VERSION_1_8

configurations {
    compileOnly {
        extendsFrom annotationProcessor
    }
}

repositories {
    mavenCentral()
}

dependencies {
    testImplementation 'org.junit.jupiter:junit-jupiter:5.6.2'
}

test {
    useJUnitPlatform()
}

 

follow us on