Queue and Stack Which brackets are balanced
You're dealing with a string consisting of brackets. Write a program to examine whether the pairs of "{", "}", "(", ")", "[", "]" are correct or balanced. This means that each opening bracket must have a corresponding closing one (and vice versa) and they must go in the correct order.
For example, the program should print true for the string [()]{}{()()} and false for ()[]}.
The classic algorithm for solving this problem relies on using a stack.
create an instance of a stack;
traverse the input string;
if the current character is a starting bracket "(" or "{" or "[" then push it to the stack;
if the current is a closing bracket ")" or "}" or "]" then remove (pop) the top element from the stack. If the popped bracket does not match the starting bracket then parentheses are not balanced;
if there are some starting brackets left in the stack after completing traversal, then the parentheses are not balanced.
Report a typo
Sample Input 1:
([][])
Sample Output 1:
true
Sample Input 2:
true
Sample Input 3:
{{[()]]
Sample Output 3:
false
import java.util.*;
public class Main {
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
String str = in.nextLine();
Stack<Character> stack = new Stack<>();
boolean balanced = false;
char a;
char b;
for (int i = 0; i < str.length(); i++) {
a = str.charAt(i);
if (a == '(' || a == '[' || a == '{') {
stack.push(a);
} else {
if (a == ')' || a == ']' || a == '}') {
if (stack.size() == 0) {
balanced = false;
break;
}
b = stack.pop();
if ((b == '{' && a == '}') || (b == '[' && a == ']') || (b == '(' && a == ')')) {
balanced = true;
} else {
balanced = false;
break;
}
}
}
}
if (stack.size() > 0) {
balanced = false;
}
System.out.println(balanced);
}
}
import java.util.ArrayDeque;
import java.util.Scanner;
class Main {
public static void main(String[] args) {
// put your code here
Scanner scanner = new Scanner(System.in);
ArrayDeque<Character> brackets = new ArrayDeque<>();
String openingBrackets = "({[";
String closingBrackets = ")}]";
char[] input = scanner.nextLine().toCharArray();
boolean matched = true;
for (char c : input) {
if (openingBrackets.indexOf(c) > -1) {
brackets.push(c);
matched = false;
} else if (closingBrackets.indexOf(c) > -1) {
Character b = brackets.pollFirst();
matched = b != null && openingBrackets.indexOf(b) == closingBrackets.indexOf(c);
}
}
System.out.println(matched && brackets.size() == 0);
}
}

浙公网安备 33010602011771号