Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.ArrayDeque;
- import java.util.Scanner;
- public class BalancedParentheses {
- public static void main(String[] args) {
- Scanner scanner = new Scanner(System.in);
- String input = scanner.nextLine();
- ArrayDeque<Character> stack = new ArrayDeque<>();
- boolean areBalanced = true;
- for (int i = 0; i < input.length(); i++) {
- char temp = input.charAt(i);
- if (temp == '[' || temp == '{' || temp == '(') {
- stack.push(temp);
- } else {
- if (stack.isEmpty()) {
- areBalanced = false;
- break;
- }
- char closingBracket = stack.pop();
- if ((closingBracket == '{' && temp != '}' || closingBracket == '[' && temp != ']' ||
- closingBracket == '(' && temp != ')')) {
- areBalanced = false;
- break;
- }
- }
- }
- if (areBalanced) {
- System.out.println("YES");
- } else {
- System.out.println("NO");
- }
- }
- }
Add Comment
Please, Sign In to add comment