Below code is to check whether the given string has balanced parantheses or not using stack. Getting wrong output for input "[]". It should print true but the result that i am getting is false.
import java.util.*;
class Solution{
public static void main(String[] argh) {
Scanner sc = new Scanner(System.in);
Stack st = new Stack();
boolean flag = true;
while (sc.hasNext()) {
String input = sc.next();
//Complete the code
for (int i = 0; i < input.length(); i++) {
flag = false;
if ((input.charAt(i) == '{') || (input.charAt(i) == '(') || (input.charAt(i) == '[')) {
st.push(input.charAt(i));
continue;
}
if ((input.charAt(i) == '}') || (input.charAt(i) == ')') || (input.charAt(i) == ']')) {
if (st.isEmpty()) {
flag = false;
} else {
char item = (char) st.pop();
if ((item == '(') && (input.charAt(i) == ')'))
flag = true;
if ((item == '{') && (input.charAt(i) == '}'))
flag = true;
if ((item == '[') && (input.charAt(i) == ']'))
flag = true;
}
}
}
if (!st.isEmpty())
flag = false;
System.out.println(flag);
}
}
}