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)