mirror of
https://github.com/TheAlgorithms/Java.git
synced 2025-07-06 17:29:31 +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;
|
||||
}
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
Reference in New Issue
Block a user