How can you reverse a string using stack? Give one example and show how you can reverse a given string using stack.
Given a string, reverse it using stack.
Example:
Input: str = “GeeksQuiz”
Output: ziuQskeeGInput: str = “abc”
Output: cba
Approach:
The idea is to create an empty stack and push all the characters from the string into it. Then pop each character one by one from the stack and put them back into the input string starting from the 0’th index. As we all know, stacks work on the principle of first in, last out. After popping all the elements and placing them back to string, the formed string would be reversed.
Follow the steps given below to reverse a string using stack.
- Create an empty stack.
- One by one push all characters of string to stack.
- One by one pop all characters from stack and put them back to string.
Below is the implementation of the above approach:
- C++
- C
- Java
- Python3
- C#
- Javascript
Reversed string is ziuQskeeG
Time Complexity: O(N)
Auxiliary Space: O(N) for Stack.
Tirthankar Pal
MBA from IIT Kharagpur with GATE, GMAT, IIT Kharagpur Written Test, and Interview
2 year PGDM (E-Business) from Welingkar, Mumbai
4 years of Bachelor of Science (Hons) in Computer Science from the National Institute of Electronics and Information Technology
Google and Hubspot Certification
Brain Bench Certification in C++, VC++, Data Structure and Project Management
10 years of Experience in Software Development out of that 6 years 8 months in Wipro
Selected in Six World Class UK Universities:-
King's College London, Durham University, University of Exeter, University of Sheffield, University of Newcastle, University of Leeds
No comments:
Post a Comment