Java Program to Reverse a String using Stack
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:
- Push the character one by one into the Stack of datatype character.
- Pop the character one by one from the Stack until the stack becomes empty.
- Add a popped element to the character array.
- Convert character array to string.
- Return reversed string.
Below is the implementation of the above approach.
Java
import java.io.*;
import java.util.*;
class GFG {
public static String ReverseString(String str)
{
char [] reverseString = new char [str.length()];
Stack<Character> stack = new Stack<Character>();
for ( int i = 0 ; i < str.length(); i++) {
stack.push(str.charAt(i));
}
int i = 0 ;
while (!stack.isEmpty()) {
reverseString[i++] = stack.pop();
}
return new String(reverseString);
}
public static void main(String[] args)
{
String str1 = "GeeksForGeeks" ;
System.out.println(str1 + " <- Reverse -> "
+ ReverseString(str1));
String str2 = "Hello World" ;
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.
Last Updated :
21 Oct, 2020
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...