DEV Community 👩‍💻👨‍💻

DEV Community 👩‍💻👨‍💻 is a community of 963,673 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Create account Log in
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)

Take a look at this:

Settings

Go to your customization settings to nudge your home feed to show content more relevant to your developer experience level. 🛠