Computer scienceProgramming languagesJavaWorking with dataCollectionsCollection implementationsThe Collection hierarchy implementations

ArrayDeque

Reverse string

Report a typo

You are given a string of characters. Your task is to write a function in Java that uses an ArrayDeque to reverse this string.

Input: The function will receive a single argument—a string s, representing the string of characters.

Output: The function should return a String, which is the reversed version of the input string s.

Sample Input 1:

Hello, World!

Sample Output 1:

!dlroW ,olleH
Write a program in Java 17
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.Scanner;

public class Main {
public static String reverseString(String s) {
Deque<Character> stack = new ArrayDeque<>();

// Push all characters of the string onto the stack
for (char ch : s.toCharArray()) {
stack.push(ch);
}

StringBuilder reversed = new StringBuilder(s.length());
while (!stack.isEmpty()) {
// Pop the characters off the stack and append them to the result
...
}
...
}

public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String inputStr = scanner.nextLine();
System.out.println(reverseString(inputStr));
}
}

Create a free account to access the full topic