The two-pointer method is the best because it reverses the word directly without using extra memory.
Key takeaways:
Two pointers method: This approach is great for reversing a word in-place without using extra memory. It involves swapping characters from both ends of the word.
STL reverse function: By including
#include <algorithm>
, we can reverse a word with just one function call, making it a quick solution.Recursive approach: We swap characters by repeated function calls.
Using a stack: By taking the benefit of the stack's LIFO (last in, first out) property, we can reverse a word by pushing characters into the stack and popping them.
Reversing a word in C++ is a common exercise to understand string manipulation. It has various applications, such as palindrome checking, which verifies whether a word reads the same backward and forward and in cryptography to encode/decode the text. In this answer, we'll explore four different ways to reverse a word in C++.
Using two-pointers
Using the reverse
function
Using recursion
Using a stack
The two-pointer approach to reverse a word works by placing one pointer at the start of the word and the other at the end. Both pointers then move towards each other. At each stage, we swap the characters at the positions of the two pointers.
To reverse a word
using two pointers, follow the steps below:
Initialize two pointers start
and end
, with value word.length - 1
.
Start a loop, and swap the characters at start
and end
position. After swapping, increment and decrement the values of satrt
and end
respectively by
Continue until start
becomes greater than or equal to the end
.
Let's see the code for this approach:
#include <iostream>void reverseWord(std::string& word) {// Initialize two pointersint start = 0;int end = word.length() - 1;// Continue swapping until 'start' become greater than or equal to 'end'while (start < end) {// Swap the characters at 'start' and 'end'.std::swap(word[start], word[end]);// Move the 'start' pointer one step to the end.start++;// Move the 'end' pointer one step to the start.end--;}}//Driver codeint main() {std::string word = "educative";std::cout << "Original word: " << word << std::endl;reverseWord(word);std::cout << "Reversed word: " << word << std::endl;return 0;}
reverse
functionC++ has a built-in function called reverse
which is part of the Standard Template Library (STL). The function takes the start and end of the word and returns the reverse of that word. The reverse function is included in <algorithm>
library, therefore, #include <algorithm>
is needed.
To reverse a word
using the reverse
function, follow the steps below:
Include algorithm library.
Get the start
and end
of the word.
Call the reverse
function by passing start
and end
of the word as argument.
Let's see the code for this approach:
#include <iostream>#include <algorithm>// Driver codeint main() {std::string word = "educative";std::cout << "Original word: " << word << std::endl;// Calling the reverse functionreverse(word.begin(), word.end());std::cout << "Reversed word: " << word << std::endl;return 0;}
We can also use recursion to reverse a word. Recursion is the process of solving a problem by calling itself repeatedly on smaller pieces of the problem and stopping when we reach a base case. To reverse a string using recursion, we will repeatedly call a function and will stop when start
pointer becomes greater than or equal end
pointer.
The steps for writing the recursive function are given below:
Swap the characters at the position start
and end
.
Call the recursive function by incrementing and decrementing start
and end
by
Check for the base case that is if the starting position is greater than or equal to the ending position. If so, it means we have reversed the whole word, and there's no need to keep going with the recursion.
Let's see the code for this approach:
#include <iostream>void reverseWordRecursively(std::string& word, int start, int end) {// Base case: if the start index is greater than or equal to the end, stop the recursionif (start >= end) {return;}// Swap the characters at the start and end positionsstd::swap(word[start], word[end]);// Recursive call with updated indicesreverseWordRecursively(word, start + 1, end - 1);}//Driver codeint main() {std::string word = "educative";std::cout << "Original word: " << word << std::endl;reverseWordRecursively(word, 0, word.length() - 1);std::cout << "Reversed word: " << word << std::endl;return 0;}
We can also reverse a word by using a stack. A stack is a data structure that follows the LIFO (last in, first out) principle; the previous item we put into the stack is the first one to come out. Using this stack property, we can reverse a word by putting all the characters of a word in the stack and then retrieving them back in the reverse order.
The steps to reverse a word by using a stack are as follows:
Initialize a stack.
Put each character in the word
into the stack.
Empty the word
to store its reversed characters.
Retrieve all the characters back from the stack and store them in the word
.
Let's see the code for this approach:
#include <iostream>#include <stack>void reverseWithStack(std::string& word) {std::stack<char> wordStack;// Push each character of the word into the wordStackfor (char ch : word) {wordStack.push(ch);}// Clear the word to store the reversed charactersword = "";// Pop (retrieve) characters from the wordStack to reverse the wordwhile (!wordStack.empty()) {word += wordStack.top();wordStack.pop();}}//Driver codeint main() {std::string word = "educative";std::cout << "Original word: " << word << std::endl;reverseWithStack(word);std::cout << "Reversed word: " << word << std::endl;return 0;}
Each method is practical and fulfills different needs according to the requirements or maybe any given constraints. For example:
Using a two-pointer approach is useful when we want to reverse a word in place without using any extra memory.
Using built-in reverse
function is helpful when we do not want to write our own implementation and quickly want to reverse a word.
Using the recursion approach is useful when we want to demonstrate how recursion can be used to solve different day to day programming tasks.
Using the stack is suitable for a data structure to reverse a given word.
Haven’t found what you were looking for? Contact Us
Free Resources