1
I’m making a program that takes a string and checks if open parentheses are closed. I have the following code:
int abertos = 0, fechados = 0; //conta os parenteses
parens = parens.replaceAll("[^()]", "");//fiz essa linha considerando que a entrada contenha caracteres que não sejam parenteses
for (int i = 0; i < parens.length(); i++){
if (parens.charAt(i) == '(')
abertos++;
if (parens.charAt(i) == ')')
fechados++;
return abertos == fechados ? true : false;
}
If the input is " () " or " )("it returns true, but everyone agrees that " )( " are not closed parentheses, so I need a script to resolve this situation. But, what? I spent a couple of hours cracking my head and I did not find the answer, I ask the help of readers!
You can use a stack, and each time you close a parentheses it will take out one of this stack, if what you take out does not match, it means it closed wrong
– Natan Fernandes
Thank you very much Natan, I am beginner and still did not know the Stack class, helped me a lot!
– Sampaux