Skip to content

Commit bf2fc48

Browse files
added method in valid parentheses
1 parent b190cb7 commit bf2fc48

File tree

2 files changed

+43
-21
lines changed

2 files changed

+43
-21
lines changed

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

+40-21
Original file line numberDiff line numberDiff line change
@@ -12,30 +12,49 @@ public static boolean isValid(String s) {
1212
int head = 0;
1313
for (char c : s.toCharArray()) {
1414
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] != '[') {
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] != '[') {
32+
return false;
33+
}
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+
47+
for (char ch : s.toCharArray()) {
48+
if (openBrackets.indexOf(ch) != -1) {
49+
stack[++i] = ch;
50+
} else {
51+
if (i >= 0 && openBrackets.indexOf(stack[i]) == closeBrackets.indexOf(ch)) {
52+
i--;
53+
} else {
3254
return false;
3355
}
34-
break;
35-
default:
36-
throw new IllegalArgumentException("Unexpected character: " + c);
3756
}
3857
}
39-
return head == 0;
58+
return i == -1;
4059
}
4160
}

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

+3
Original file line numberDiff line numberDiff line change
@@ -10,15 +10,18 @@ public class ValidParenthesesTest {
1010
@Test
1111
void testOne() {
1212
assertTrue(ValidParentheses.isValid("()"));
13+
assertTrue(ValidParentheses.isValidParentheses("()"));
1314
}
1415

1516
@Test
1617
void testTwo() {
1718
assertTrue(ValidParentheses.isValid("()[]{}"));
19+
assertTrue(ValidParentheses.isValidParentheses("()[]{}"));
1820
}
1921

2022
@Test
2123
void testThree() {
2224
assertFalse(ValidParentheses.isValid("(]"));
25+
assertFalse(ValidParentheses.isValidParentheses("(]"));
2326
}
2427
}

0 commit comments

Comments
 (0)