Correspondencia de paréntesis / corchetes utilizando el algoritmo de pila
Por ejemplo, si los paréntesis / corchetes coinciden en lo siguiente:
({})
(()){}()
()
y así sucesivamente, pero si los paréntesis / paréntesis no coinciden, debería devolver falso, por ejemplo:
{}
({}(
){})
(()
y así. ¿Puedes por favor revisar este código? Gracias por adelantado.
public static boolean isParenthesisMatch(String str) {
Stack<Character> stack = new Stack<Character>();
char c;
for(int i=0; i < str.length(); i++) {
c = str.charAt(i);
if(c == '{')
return false;
if(c == '(')
stack.push(c);
if(c == '{') {
stack.push(c);
if(c == '}')
if(stack.empty())
return false;
else if(stack.peek() == '{')
stack.pop();
}
else if(c == ')')
if(stack.empty())
return false;
else if(stack.peek() == '(')
stack.pop();
else
return false;
}
return stack.empty();
}
public static void main(String[] args) {
String str = "({})";
System.out.println(Weekly12.parenthesisOtherMatching(str));
}