diff --git a/src/main/java/com/thealgorithms/stacks/BalancedBrackets.java b/src/main/java/com/thealgorithms/stacks/BalancedBrackets.java index a8f5254b..d3077ff5 100644 --- a/src/main/java/com/thealgorithms/stacks/BalancedBrackets.java +++ b/src/main/java/com/thealgorithms/stacks/BalancedBrackets.java @@ -59,26 +59,22 @@ final class BalancedBrackets { switch (bracket) { case '(': case '[': + case '<': case '{': bracketsStack.push(bracket); break; case ')': case ']': + case '>': case '}': if (bracketsStack.isEmpty() || !isPaired(bracketsStack.pop(), bracket)) { return false; } break; default: - /* other character is invalid */ return false; } } return bracketsStack.isEmpty(); } - - public static void main(String[] args) { - assert isBalanced("[()]{}{[()()]()}"); - assert !isBalanced("[(])"); - } } diff --git a/src/test/java/com/thealgorithms/stacks/BalancedBracketsTest.java b/src/test/java/com/thealgorithms/stacks/BalancedBracketsTest.java new file mode 100644 index 00000000..33ef18af --- /dev/null +++ b/src/test/java/com/thealgorithms/stacks/BalancedBracketsTest.java @@ -0,0 +1,36 @@ +package com.thealgorithms.stacks; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; + +class BalancedBracketsTest { + + @ParameterizedTest + @CsvSource({"(, )", "[, ]", "{, }", "<, >"}) + void testIsPairedTrue(char opening, char closing) { + assertTrue(BalancedBrackets.isPaired(opening, closing)); + } + + @ParameterizedTest + @CsvSource({"(, ]", "[, )", "{, >", "<, )", "a, b", "!, @"}) + void testIsPairedFalse(char opening, char closing) { + assertFalse(BalancedBrackets.isPaired(opening, closing)); + } + + @ParameterizedTest + @CsvSource({"'[()]{}{[()()]()}', true", "'()', true", "'[]', true", "'{}', true", "'<>', true", "'[{<>}]', true", "'', true", "'[(])', false", "'([)]', false", "'{[<]>}', false", "'[', false", "')', false", "'[{', false", "']', false", "'[a+b]', false", "'a+b', false"}) + void testIsBalanced(String input, boolean expected) { + assertEquals(expected, BalancedBrackets.isBalanced(input)); + } + + @Test + void testIsBalancedNull() { + assertThrows(IllegalArgumentException.class, () -> BalancedBrackets.isBalanced(null)); + } +}