DEV Community

Sadiul Hakim
Sadiul Hakim

Posted on

Algorithm part 3 : Reverse a string using Stack

Hey, Guys. Today i will show you how you can reverse a string using stack.

In this problem we are given a single string and we have to reverse it using stack.

Solution

public String reverse(String str) {
        Stack<Character> stack = new Stack<>();

        for (int i = 0; i < str.length(); i++) {
            stack.push(str.charAt(i));
        }

        char[] arr = new char[stack.size()];
        int i = 0;
        while (!stack.empty()) {
            arr[i] = (char) stack.pop();
            i++;
        }

        return new String(arr);

    }
Enter fullscreen mode Exit fullscreen mode

Hope this helps you. Thank you ❤.

Top comments (0)

Image of PulumiUP 2025

Let's talk about the current state of cloud and IaC, platform engineering, and security.

Dive into the stories and experiences of innovators and experts, from Startup Founders to Industry Leaders at PulumiUP 2025.

Register Now

👋 Kindness is contagious

Dive into this insightful write-up, celebrated within the collaborative DEV Community. Developers at any stage are invited to contribute and elevate our shared skills.

A simple "thank you" can boost someone’s spirits—leave your kudos in the comments!

On DEV, exchanging ideas fuels progress and deepens our connections. If this post helped you, a brief note of thanks goes a long way.

Okay