refactor: BalancedBrackets (#5391)

This commit is contained in:
Alex Klymenko 2024-08-25 22:21:30 +02:00 committed by GitHub
parent 580aa0c9c5
commit 7e9cdad3ee
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 38 additions and 6 deletions

View File

@ -59,26 +59,22 @@ final class BalancedBrackets {
switch (bracket) { switch (bracket) {
case '(': case '(':
case '[': case '[':
case '<':
case '{': case '{':
bracketsStack.push(bracket); bracketsStack.push(bracket);
break; break;
case ')': case ')':
case ']': case ']':
case '>':
case '}': case '}':
if (bracketsStack.isEmpty() || !isPaired(bracketsStack.pop(), bracket)) { if (bracketsStack.isEmpty() || !isPaired(bracketsStack.pop(), bracket)) {
return false; return false;
} }
break; break;
default: default:
/* other character is invalid */
return false; return false;
} }
} }
return bracketsStack.isEmpty(); return bracketsStack.isEmpty();
} }
public static void main(String[] args) {
assert isBalanced("[()]{}{[()()]()}");
assert !isBalanced("[(])");
}
} }

View File

@ -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));
}
}