Skip to content
Related Articles

Related Articles

Improve Article

Java Program to Reverse a String using Stack

  • Difficulty Level : Easy
  • Last Updated : 21 Oct, 2020

The Stack is a linear data structure that follows the LIFO(Last In First Out) principle, i.e, the element inserted at the last is the element to come out first.

Approach:

  1. Push the character one by one into the Stack of datatype character.
  2. Pop the character one by one from the Stack until the stack becomes empty.
  3. Add a popped element to the character array.
  4. Convert character array to string.
  5. Return reversed string.

Below is the implementation of the above approach.

Java




// Java Program to Reverse a String using Stack
  
import java.io.*;
import java.util.*;
  
class GFG {
  
    public static String ReverseString(String str)
    {
        char[] reverseString = new char[str.length()];
        // Declare a stack of type Character
        Stack<Character> stack = new Stack<Character>();
  
        // Traverse the String and push the character one by
        // one into the Stack
        for (int i = 0; i < str.length(); i++) {
            // push the character into the Stack
            stack.push(str.charAt(i));
        }
  
        // Now Pop the Characters from the stack until it
        // becomes empty
  
        int i = 0;
        while (!stack.isEmpty()) { // popping element until
                                   // stack become empty
            // get the character from the top of the stack
            reverseString[i++] = stack.pop();
        }
        // return string object
        return new String(reverseString);
    }
  
    // Driver code
    public static void main(String[] args)
    {
        String str1 = "GeeksForGeeks";
        
        // call the function
        System.out.println(str1 + " <- Reverse -> "
                           + ReverseString(str1));
        
        String str2 = "Hello World";
        
        // call the function
        System.out.println(str2 + " <- Reverse -> "
                           + ReverseString(str2));
    }
}

Output:

GeeksForGeeks <- Reverse -> skeeGroFskeeG
Hello World <- Reverse -> dlroW olleH

Time Complexity: O(n), where n is a number of characters in the stack.

Auxiliary Space: O(n) for the stack.

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.




My Personal Notes arrow_drop_up
Recommended Articles
Page :