Write an iterative program to reverse a string in C++ and Java.

For example,

Input:  Hello, World
 
Output: dlroW ,olleH

1. Using built-in methods

A simple approach is to use strrev() function in C, or std::reverse in C++, or StringBuilder.reverse() method in Java.

C++


Download  Run Code

Java


Download  Run Code

2. Using Stack

We can easily reverse a given string using the stack data structure. The idea is to push each character of the string into a stack and then start filling the input string (starting from index 0) by popping characters from the stack until it is empty.

Following is the C++ and Java implementation of the idea:

C++


Download  Run Code

Java


Download  Run Code

The time complexity of the above solution is O(n) and the auxiliary space used by the program is O(n) for stack.

3. In-place conversion

The above solution takes O(n) for stack data structure which is not recommended. We can easily solve this problem in linear time and constant space. Following is the iterative in-place solution in C++ and Java:

C++


Download  Run Code

Java


Download  Run Code

 
Related Posts:

Reverse a string using recursion – C, C++, and Java