Skip to content

Commit 6c30495

Browse files
authored
refactor: optimize ValidParentheses methods and add parameterized tests (#6352)
1 parent fa2ca9d commit 6c30495

File tree

2 files changed

+46
-64
lines changed

2 files changed

+46
-64
lines changed
Lines changed: 39 additions & 45 deletions
Original file line numberDiff line numberDiff line change
@@ -1,59 +1,53 @@
11
package com.thealgorithms.strings;
2-
// Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine
3-
// if the input string is valid. An input string is valid if: Open brackets must be closed by
4-
// the same type of brackets. Open brackets must be closed in the correct order. Every close
5-
// bracket has a corresponding open bracket of the same type.
62

3+
import java.util.ArrayDeque;
4+
import java.util.Deque;
5+
import java.util.Map;
6+
7+
/**
8+
* Validates if a given string has valid matching parentheses.
9+
* <p>
10+
* A string is considered valid if:
11+
* <ul>
12+
* <li>Open brackets are closed by the same type of brackets.</li>
13+
* <li>Brackets are closed in the correct order.</li>
14+
* <li>Every closing bracket has a corresponding open bracket of the same type.</li>
15+
* </ul>
16+
*
17+
* Allowed characters: '(', ')', '{', '}', '[', ']'
18+
*/
719
public final class ValidParentheses {
820
private ValidParentheses() {
921
}
22+
23+
private static final Map<Character, Character> BRACKET_PAIRS = Map.of(')', '(', '}', '{', ']', '[');
24+
25+
/**
26+
* Checks if the input string has valid parentheses.
27+
*
28+
* @param s the string containing only bracket characters
29+
* @return true if valid, false otherwise
30+
* @throws IllegalArgumentException if the string contains invalid characters or is null
31+
*/
1032
public static boolean isValid(String s) {
11-
char[] stack = new char[s.length()];
12-
int head = 0;
33+
if (s == null) {
34+
throw new IllegalArgumentException("Input string cannot be null");
35+
}
36+
37+
Deque<Character> stack = new ArrayDeque<>();
38+
1339
for (char c : s.toCharArray()) {
14-
switch (c) {
15-
case '{':
16-
case '[':
17-
case '(':
18-
stack[head++] = c;
19-
break;
20-
case '}':
21-
if (head == 0 || stack[--head] != '{') {
22-
return false;
23-
}
24-
break;
25-
case ')':
26-
if (head == 0 || stack[--head] != '(') {
27-
return false;
28-
}
29-
break;
30-
case ']':
31-
if (head == 0 || stack[--head] != '[') {
40+
if (BRACKET_PAIRS.containsValue(c)) {
41+
stack.push(c); // opening bracket
42+
} else if (BRACKET_PAIRS.containsKey(c)) {
43+
if (stack.isEmpty() || stack.pop() != BRACKET_PAIRS.get(c)) {
3244
return false;
3345
}
34-
break;
35-
default:
36-
throw new IllegalArgumentException("Unexpected character: " + c);
37-
}
38-
}
39-
return head == 0;
40-
}
41-
public static boolean isValidParentheses(String s) {
42-
int i = -1;
43-
char[] stack = new char[s.length()];
44-
String openBrackets = "({[";
45-
String closeBrackets = ")}]";
46-
for (char ch : s.toCharArray()) {
47-
if (openBrackets.indexOf(ch) != -1) {
48-
stack[++i] = ch;
4946
} else {
50-
if (i >= 0 && openBrackets.indexOf(stack[i]) == closeBrackets.indexOf(ch)) {
51-
i--;
52-
} else {
53-
return false;
54-
}
47+
throw new IllegalArgumentException("Unexpected character: " + c);
5548
}
5649
}
57-
return i == -1;
50+
51+
return stack.isEmpty();
5852
}
5953
}
Lines changed: 7 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1,27 +1,15 @@
11
package com.thealgorithms.strings;
22

3-
import static org.junit.jupiter.api.Assertions.assertFalse;
4-
import static org.junit.jupiter.api.Assertions.assertTrue;
3+
import static org.junit.jupiter.api.Assertions.assertEquals;
54

6-
import org.junit.jupiter.api.Test;
5+
import org.junit.jupiter.params.ParameterizedTest;
6+
import org.junit.jupiter.params.provider.CsvSource;
77

88
public class ValidParenthesesTest {
99

10-
@Test
11-
void testOne() {
12-
assertTrue(ValidParentheses.isValid("()"));
13-
assertTrue(ValidParentheses.isValidParentheses("()"));
14-
}
15-
16-
@Test
17-
void testTwo() {
18-
assertTrue(ValidParentheses.isValid("()[]{}"));
19-
assertTrue(ValidParentheses.isValidParentheses("()[]{}"));
20-
}
21-
22-
@Test
23-
void testThree() {
24-
assertFalse(ValidParentheses.isValid("(]"));
25-
assertFalse(ValidParentheses.isValidParentheses("(]"));
10+
@ParameterizedTest(name = "Input: \"{0}\" → Expected: {1}")
11+
@CsvSource({"'()', true", "'()[]{}', true", "'(]', false", "'{[]}', true", "'([{}])', true", "'([)]', false", "'', true", "'(', false", "')', false"})
12+
void testIsValid(String input, boolean expected) {
13+
assertEquals(expected, ValidParentheses.isValid(input));
2614
}
2715
}

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy