We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
This one was a bit tricky. You can't just check if this character is equal to what's on the stack because it must be the opposite bracket, parenthese, etc. for it to be "equally bracketed." You also have to make sure that the stack isn't empty before you peek -> or else you get a null-pointer.
Scanner sc = new Scanner(System.in);
while (sc.hasNext()) {
String input=sc.next();
Stack<Character> stacky = new Stack<>();
for (int i = 0; i < input.length(); i++) {
if (!stacky.isEmpty()) {
switch(input.charAt(i)) {
case '}' : if (stacky.peek() == '{') {
stacky.pop();
} break;
case ']' : if (stacky.peek() == '[') {
stacky.pop();
} break;
case ')' : if (stacky.peek() == '(') {
stacky.pop();
} break;
default: stacky.push(input.charAt(i));
}
} else {
stacky.push(input.charAt(i));
}
}
System.out.println(stacky.isEmpty());
}
Java Stack
You are viewing a single comment's thread. Return to all comments →
This one was a bit tricky. You can't just check if this character is equal to what's on the stack because it must be the opposite bracket, parenthese, etc. for it to be "equally bracketed." You also have to make sure that the stack isn't empty before you peek -> or else you get a null-pointer.