refactor: BalancedBrackets
(#5391)
This commit is contained in:
parent
580aa0c9c5
commit
7e9cdad3ee
@ -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("[(])");
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
@ -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));
|
||||||
|
}
|
||||||
|
}
|
Loading…
Reference in New Issue
Block a user