Skip to content

Commit 47d1ec6

Browse files
committed
fix: update ValidParentheses and tests for coverage & formatting
1 parent 4c819ee commit 47d1ec6

2 files changed

Lines changed: 8 additions & 28 deletions

File tree

src/main/java/com/thealgorithms/stacks/ValidParentheses.java

Lines changed: 5 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -13,9 +13,7 @@ private ValidParentheses() {
1313
throw new AssertionError("Cannot instantiate utility class");
1414
}
1515

16-
private static final Map<Character, Character> PAIRS = Map.of(
17-
')', '(', '}', '{', ']', '['
18-
);
16+
private static final Map<Character, Character> PAIRS = Map.of(')', '(', '}', '{', ']', '[');
1917

2018
/**
2119
* Checks if the input string has valid parentheses.
@@ -24,18 +22,13 @@ private ValidParentheses() {
2422
* @return true if valid, false otherwise
2523
*/
2624
public static boolean isValid(final String s) {
27-
if (s == null) {
28-
throw new NullPointerException("Input cannot be null");
29-
}
30-
25+
if (s == null) throw new NullPointerException("Input cannot be null");
3126
Deque<Character> stack = new ArrayDeque<>();
3227
for (char ch : s.toCharArray()) {
33-
if (PAIRS.containsValue(ch)) { // opening bracket
28+
if (PAIRS.containsValue(ch)) {
3429
stack.push(ch);
35-
} else if (PAIRS.containsKey(ch)) { // closing bracket
36-
if (stack.isEmpty() || stack.pop() != PAIRS.get(ch)) {
37-
return false;
38-
}
30+
} else if (PAIRS.containsKey(ch)) {
31+
if (stack.isEmpty() || stack.pop() != PAIRS.get(ch)) return false;
3932
}
4033
}
4134
return stack.isEmpty();

src/test/java/com/thealgorithms/stacks/ValidParenthesesTest.java

Lines changed: 3 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -12,32 +12,19 @@
1212
public class ValidParenthesesTest {
1313

1414
@ParameterizedTest
15-
@CsvSource({
16-
"'()', true",
17-
"'()[]{}', true",
18-
"'{[]}', true",
19-
"'', true"
20-
})
15+
@CsvSource({"'()', true", "'()[]{}', true", "'{[]}', true", "'', true"})
2116
void testValidParentheses(String input, boolean expected) {
2217
assertEquals(expected, ValidParentheses.isValid(input));
2318
}
2419

2520
@ParameterizedTest
26-
@CsvSource({
27-
"'(', false",
28-
"')', false",
29-
"'([)]', false",
30-
"'{[}]', false",
31-
"'((()', false"
32-
})
21+
@CsvSource({"'(', false", "')', false", "'([)]', false", "'{[}]', false", "'((()', false"})
3322
void testInvalidParentheses(String input, boolean expected) {
3423
assertEquals(expected, ValidParentheses.isValid(input));
3524
}
3625

3726
@ParameterizedTest
38-
@CsvSource({
39-
"null"
40-
})
27+
@CsvSource({"null"})
4128
void testNullInput(String input) {
4229
assertThrows(NullPointerException.class, () -> ValidParentheses.isValid(null));
4330
}

0 commit comments

Comments
 (0)