A Stack is a linear data structure that follows the LIFO (Last In, First Out) principle. This property makes a stack useful for reversing a string because the last character inserted into the stack is the first character removed.
- Stack follows the LIFO principle.
- Each character is pushed into the stack.
- Characters are popped in reverse order.
Example
Input: GeeksForGeeks
Output: skeeGroFskeeG
Approach
- Create a Stack<Character> to store the characters of the string.
- Traverse the string and push each character into the stack.
- Pop characters from the stack until it becomes empty.
- Store each popped character in a character array.
- Convert the character array into a String and return it.
import java.util.Stack;
public class GFG {
// Method to reverse a string using Stack
static String reverseString(String str) {
Stack<Character> stack = new Stack<>();
// Push each character into the stack
for (int i = 0; i < str.length(); i++) {
stack.push(str.charAt(i));
}
// Store the reversed characters
char[] reversed = new char[str.length()];
int i = 0;
// Pop characters from the stack
while (!stack.isEmpty()) {
reversed[i++] = stack.pop();
}
return new String(reversed);
}
public static void main(String[] args) {
String str1 = "GeeksForGeeks";
String str2 = "Hello World";
System.out.println("Original: " + str1);
System.out.println("Reversed: " + reverseString(str1));
System.out.println("Original: " + str2);
System.out.println("Reversed: " + reverseString(str2));
}
}
Output
Original: GeeksForGeeks Reversed: skeeGroFskeeG Original: Hello World Reversed: dlroW olleH
Explanation
- Create a
Stack<Character>to store the string characters. - Push each character into the stack.
- Pop characters one by one to get them in reverse order.
- Store the popped characters in a character array.
- Convert the array into a
Stringand return it.