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;
}
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;
}
}