mirror of
https://github.com/TheAlgorithms/Java.git
synced 2025-07-07 17:56:02 +08:00
Add another method to check valid parentheses in ValidParentheses.java (#5616)
This commit is contained in:

committed by
GitHub

parent
732f7c8458
commit
4a5bf39f8e
@ -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;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
@ -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("(]"));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
Reference in New Issue
Block a user