Add another method to check valid parentheses in ValidParentheses.java (#5616)

This commit is contained in:
Taranjeet Singh Kalsi
2024-10-08 00:18:02 +05:30
committed by GitHub
parent 732f7c8458
commit 4a5bf39f8e
2 changed files with 21 additions and 0 deletions

View File

@ -38,4 +38,22 @@ public final class ValidParentheses {
} }
return head == 0; return head == 0;
} }
public static boolean isValidParentheses(String s) {
int i = -1;
char[] stack = new char[s.length()];
String openBrackets = "({[";
String closeBrackets = ")}]";
for (char ch : s.toCharArray()) {
if (openBrackets.indexOf(ch) != -1) {
stack[++i] = ch;
} else {
if (i >= 0 && openBrackets.indexOf(stack[i]) == closeBrackets.indexOf(ch)) {
i--;
} else {
return false;
}
}
}
return i == -1;
}
} }

View File

@ -10,15 +10,18 @@ public class ValidParenthesesTest {
@Test @Test
void testOne() { void testOne() {
assertTrue(ValidParentheses.isValid("()")); assertTrue(ValidParentheses.isValid("()"));
assertTrue(ValidParentheses.isValidParentheses("()"));
} }
@Test @Test
void testTwo() { void testTwo() {
assertTrue(ValidParentheses.isValid("()[]{}")); assertTrue(ValidParentheses.isValid("()[]{}"));
assertTrue(ValidParentheses.isValidParentheses("()[]{}"));
} }
@Test @Test
void testThree() { void testThree() {
assertFalse(ValidParentheses.isValid("(]")); assertFalse(ValidParentheses.isValid("(]"));
assertFalse(ValidParentheses.isValidParentheses("(]"));
} }
} }