Given a string, reverse the string in place, so it does not create a new string. Instead, it modifies the original string.
Example 1:
str = "hi-educative"
"evitacude-ih"
Example 2:
"hi-answer!!!"
'!!!rewsna-ih'
In this algorithm, we’ll use a stack data structure to reverse the string.
A Stack is a linear data structure in which the element inserted last is the element to be deleted first.
The algorithm contains the following steps:
Here, we’ll use the STL implementation of stack in c++. Refer How to use the STL stack in C++ to learn more.
Let’s look at the demo below:
Let’s look at the code below:
#include <iostream>#include <stack>#include <string>using namespace std;void reverseString(string &str) {stack<int> stk;for (char ch: str) stk.push(ch);for (int i = 0; i < str.length(); i++) {str[i] = stk.top();stk.pop();}}int main() {string str = "hi-educative";cout << "Original String - " << str << endl;reverseString(str);cout << "Reversed String - " << str;}
reverseString()
that accepts a string and reverses it.stack
.str
string.reverseString()
method with the parameter as str.
Free Resources