Computer scienceProgramming languagesJavaWorking with dataCollectionsCollection implementationsThe Collection hierarchy implementations

ArrayDeque

A string of parentheses

Report a typo

You are given a string of parentheses. Write a function in Java that uses an ArrayDeque to determine whether the string of parentheses is balanced. A balanced string of parentheses has every opening parenthesis paired with a corresponding closing parenthesis in the correct order.

Input: A string of parentheses.
Output: A boolean—returns true if the string of parentheses is balanced, and false otherwise.

Sample Input 1:

(()

Sample Output 1:

false
Write a program in Java 25
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.Scanner;

public class Main {
public static boolean isBalanced(String s) {
Deque<Character> stack = new ArrayDeque<>();
final char openParenthesis = '(';
final char closeParenthesis = ')';

for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);

if (ch == openParenthesis) {
// Push an open parenthesis onto the stack
...
} else if (ch == closeParenthesis) {
// If the stack is empty or the top element is not an open parenthesis, the string is not balanced
...
}
}

// If the stack is not empty after processing the string, the string is not balanced
...
}

public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String seq = scanner.next();
System.out.println(isBalanced(seq));
}
}

Create a free account to access the full topic