Hello all,
I am trying to make a program that essentially takes a string of parenthesis and outputs whether or not its balanced.
Basically, every '(' will push the index of that location of the string on to the stack, while a ')' will pop it off if it's not empty. At the end, it will peek at the stack giving me the index of the first offending parenthesis. My problem now is the code below isn't working correctly... can anyone assist me in helping me figure out what i am doing wrong?? The negative one output means it is balanced correctly.
Thank you
-prince
public static int parenError( String theInput ) {
String input = theInput;
int output = 0;
Deque<Integer> stack = new ArrayDeque<Integer>();
for (int i = 0; i < input.length(); i++)
{
char c = input.charAt(i);
if (c == '(')
{
stack.push(input.indexOf(i));
}
else if (c == ')')
{
if (!stack.isEmpty())
{
stack.pop();
}
}
else
{
System.out.println("nothing");
}
}
if (!stack.isEmpty())
{
output = stack.peek();
}
else if (stack.isEmpty())
{
output = -1;
}
return output;
}
}