Stack – Reverse a String using Stack
Damith
80K views
Introduction
Learn how to reverse a String using Stack. In this example takes in an array based Stack.
Stack – Data Structure – Array-based and Linked list based implementation.
The followings are the steps to reversing a String using Stack.
- String to Char[].
- Create a Stack.
- Push all characters, one by one.
- Then Pop all characters, one by one and put into the char[].
- Finally, convert to the String.
public static String reverse(String str) {
char[] charArr = str.toCharArray();
int size = charArr.length;
Stack stack = new Stack(size);
int i;
for(i = 0; i < size; ++i) {
stack.push(charArr[i]);
}
for(i = 0; i < size; ++i) {
charArr[i] = stack.pop();
}
return String.valueOf(charArr);
}
Time complexity – O(n)
Space complexity – O(n)
Complete Example
Original post : - http://mydevgeek.com/stack-reverse-string-using-stack/
Create your playground on Tech.io
This playground was created on Tech.io, our hands-on, knowledge-sharing platform for developers.