Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.ArrayDeque;
- import java.util.Deque;
- import java.util.Scanner;
- public class P05BalancedParentheses {
- public static void main(String[] args) {
- Scanner scanner = new Scanner(System.in);
- String input = scanner.nextLine();
- if (isBalanced(input)) {
- System.out.println("YES");
- } else {
- System.out.println("NO");
- }
- }
- public static boolean isBalanced(String s) {
- Deque<Character> stack = new ArrayDeque<>();
- for (char c : s.toCharArray()) {
- if (c == '(' || c == '{' || c == '[') {
- stack.push(c);
- } else if (c == ')' && (stack.isEmpty() || stack.pop() != '(')) {
- return false;
- } else if (c == '}' && (stack.isEmpty() || stack.pop() != '{')) {
- return false;
- } else if (c == ']' && (stack.isEmpty() || stack.pop() != '[')) {
- return false;
- }
- }
- return stack.isEmpty();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment