Reverse words in a given string | Set 2
Last Updated :
30 Apr, 2023
Given string str, the task is to reverse the string by considering each word of the string, str as a single unit.
Examples:
Input: str = “geeks quiz practice code”
Output: code practice quiz geeks
Explanation:
The words in the given string are [“geeks”, “quiz”, “practice”, “code”].
Therefore, after reversing the order of the words, the required output is“code practice quiz geeks”.
Input: str = “getting good at coding needs a lot of practice”
Output: practice of lot a needs coding at good getting
In-place Reversal Approach: Refer to the article Reverse words in a given string for the in-place reversal of words followed by a reversal of the entire string.
Time Complexity: O(N)
Auxiliary Space: O(1)
Stack-based Approach: In this article, the approach to solving the problem using Stack is going to be discussed. The idea here is to push all the words of str into the Stack and then print all the elements of the Stack. Follow the steps below to solve the problem:
- Create a Stack to store each word of the string str.
- Iterate over string str, and separate each word of str by a space delimiter.
- Push all the words of str into the stack.
- Print all the elements of the stack one by one.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
void printRev(string str)
{
stack<string> st;
stringstream ss(str);
string temp;
while (getline(ss, temp, ' ' )) {
st.push(temp);
}
while (!st.empty()) {
cout << st.top() << " " ;
st.pop();
}
}
int main()
{
string str;
str = "geeks quiz practice code" ;
printRev(str);
return 0;
}
|
Java
import java.util.*;
class GFG{
static void printRev(String str)
{
Stack<String> st = new Stack<String>();
String[] ss = str.split( " " );
for (String temp : ss)
{
st.add(temp);
}
while (!st.isEmpty())
{
System.out.print(st.peek() + " " );
st.pop();
}
}
public static void main(String[] args)
{
String str;
str = "geeks quiz practice code" ;
printRev(str);
}
}
|
Python3
def printRev(strr):
strr = strr.split( " " )
st = []
for i in strr:
st.append(i)
while len (st) > 0 :
print (st[ - 1 ], end = " " )
del st[ - 1 ]
if __name__ = = '__main__' :
strr = "geeks quiz practice code"
printRev(strr)
|
C#
using System;
using System.Collections;
class GFG{
static void printRev( string str)
{
Stack st = new Stack();
String[] separator = { " " };
string [] ss = str.Split(separator,
int .MaxValue,
StringSplitOptions.RemoveEmptyEntries);
foreach ( string temp in ss)
{
st.Push(temp);
}
while (st.Count > 0)
{
Console.Write(st.Peek() + " " );
st.Pop();
}
}
public static void Main( string [] args)
{
string str;
str = "geeks quiz practice code" ;
printRev(str);
}
}
|
Javascript
<script>
function printRev(str)
{
let st = [];
let ss = str.split( " " );
for (let temp=0;temp< ss.length;temp++)
{
st.push(ss[temp]);
}
while (st.length!=0)
{
document.write(st.pop() + " " );
}
}
let str;
str = "geeks quiz practice code" ;
printRev(str);
</script>
|
Output
code practice quiz geeks
Time Complexity: O(N), where N denotes the length of the string.
Auxiliary Space: O(N)
Method #2: Using built-in python functions
- As all the words in a sentence are separated by spaces.
- We have to split the sentence by spaces using split().
- We split all the words by spaces and store them in a list.
- Reverse this list and print it.
C++
#include <bits/stdc++.h>
using namespace std;
void printRev(string lis[])
{
reverse(lis, lis + 4);
for ( int i = 0; i < 4; i++)
{
cout << lis[i] << " " ;
}
}
int main()
{
string strr[] = { "geeks" , "quiz" , "practice" , "code" };
printRev(strr);
return 0;
}
|
Java
import java.util.*;
class GFG{
static void printRev(String string)
{
String[] lis = string.split( " " , 0 );
Collections.reverse(Arrays.asList(lis));
for (String li : lis)
{
System.out.print(li + " " );
}
}
public static void main(String[] args)
{
String strr = "geeks quiz practice code" ;
printRev(strr);
}
}
|
Python3
def printRev(string):
lis = list (string.split())
lis.reverse()
print ( * lis)
if __name__ = = '__main__' :
strr = "geeks quiz practice code"
printRev(strr)
|
C#
using System;
class GFG {
static void printRev( string String)
{
string [] lis = String.Split( ' ' );
Array.Reverse(lis);
foreach ( string li in lis)
{
Console.Write(li + " " );
}
}
static void Main() {
string strr = "geeks quiz practice code" ;
printRev(strr);
}
}
|
Javascript
<script>
function printRev(string){
var lis = string.split( ' ' );
console.log(lis);
lis.reverse();
console.log(lis);
document.write(lis.join( ' ' ));
}
var strr = "geeks quiz practice code"
printRev(strr)
</script>
|
Output
code practice quiz geeks
Time Complexity : O(n), n is the number of strings.
Auxiliary Space : O(1)
Using a loop and stack in python:
Approach:
The function starts by importing the time module, which is used to measure the time taken to perform the operation.
The function defines a variable stack as an empty list, which will be used to store the words in reverse order.
The function also defines a variable word as an empty string, which will be used to store each word in the input string as it is being read.
The function then iterates over each character c in the input string s.
If the character is a space, the word variable is appended to the stack list, and the word variable is reset to an empty string to start building the next word.
If the character is not a space, it is added to the current word being built.
After all characters have been processed, the last word variable is appended to the stack list.
The function then defines a variable result as an empty string, which will be used to store the reversed string.
The function then enters a loop that pops words from the stack list in reverse order, concatenates them with a space, and adds the resulting string to the result variable.
The loop continues until all words have been popped from the stack list.
The resulting string in result is stripped of any trailing spaces and returned along with the time taken to perform the operation.
Finally, the function is called twice with two different input strings (s1 and s2) to demonstrate how the function works.
Python3
import time
def reverse_words(s):
start_time = time.time()
stack = []
word = ""
for c in s:
if c = = " " :
stack.append(word)
word = ""
else :
word + = c
stack.append(word)
result = ""
while stack:
result + = stack.pop() + " "
result = result.strip()
end_time = time.time()
return result, end_time - start_time
s1 = "geeks quiz practice code"
s2 = "getting good at coding needs a lot of practice"
result, time_taken = reverse_words(s1)
print (result)
print (f "Time taken: {time_taken} seconds" )
result, time_taken = reverse_words(s2)
print (result)
print (f "Time taken: {time_taken} seconds" )
|
Output
code practice quiz geeks
Time taken: 1.049041748046875e-05 seconds
practice of lot a needs coding at good getting
Time taken: 6.9141387939453125e-06 seconds
Time complexity: O(n), where n is the length of the input string. This is because we iterate over each character in the string once, which takes O(n) time. We also append each word to a stack, which takes O(1) time per operation.
Space complexity: O(n), where n is the length of the input string. This is because we create a stack to store the words, which can take up to O(n) space in the worst case.
Similar Reads
C++ Program To Reverse Words In A Given String
Example: Let the input string be "i like this program very much". The function should change the string to "much very program this like i" Examples: Input: s = "geeks quiz practice code" Output: s = "code practice quiz geeks" Input: s = "getting good at coding needs a lot of practice" Output: s = "p
7 min read
Reverse middle words of a string
Given a string str, print reverse all words except the first and last words. Examples: Input : Hi how are you geeks Output : Hi woh era uoy geeks Input : I am fine Output : I ma finePrint the first word.For remaining middle words, print the reverse of every word after reaching end of it. This will p
4 min read
Program to reverse words in a given string in C++
Given a sentence in the form of string str, the task is to reverse each word of the given sentence in C++. Examples: Input: str = "the sky is blue" Output: blue is sky theInput: str = "I love programming" Output: programming love I Method 1: Using STL functions Reverse the given string str using STL
6 min read
How to Reverse a String in C++?
Reversing a string means replacing the first character with the last character, second character with the second last character and so on. In this article, we will learn how to reverse a string in C++. Examples Input: str = "Hello World"Output: dlroW olleHExplanation: The last character is replaced
2 min read
How to Reverse a String in Place in C++?
In C++, reversing a string is a basic operation in programming that is required in various applications, from simple and complex algorithms. Reversing a string in place involves changing the characters of the string directly without using input-dependent additional storage. In this article, we learn
2 min read
C++ Program to Reverse a String Using Stack
Given a string, reverse it using stack. For example "GeeksQuiz" should be converted to "ziuQskeeG". Following is simple algorithm to reverse a string using stack. 1) Create an empty stack.2) One by one push all characters of string to stack.3) One by one pop all characters from stack and put them ba
4 min read
Reverse individual words with O(1) extra space
Given a string str, the task is to reverse all the individual words. Examples: Input: str = "Hello World" Output: olleH dlroW Input: str = "Geeks for Geeks" Output: skeeG rof skeeG Approach: A solution to the above problem has been discussed in this post. It has a time complexity of O(n) and uses O(
5 min read
First string from the given array whose reverse is also present in the same array
Given a string array str[], the task is to find the first string from the given array whose reverse is also present in the same array. If there is no such string then print -1.Examples: Input: str[] = {"geeks", "for", "skeeg"} Output: geeks "geeks" is the first string from the array whose reverse is
12 min read
Reverse Prefix of Word in C++
Reversing a prefix of a word is a problem in which we are given a word and a character ch, we need to reverse the segment of the word that starts at the beginning of the word and ends at the first occurrence of ch (inclusive). If ch is not present in the word, the word should remain unchanged. Examp
4 min read
Reverse alternate k characters in a string
Given a string str and an integer k, the task is to reverse alternate k characters of the given string. If characters present are less than k, leave them as it is.Examples: Input: str = "geeksforgeeks", k = 3 Output: eegksfgroeeksInput: str = "abcde", k = 2 Output: bacde Approach: The idea is to fir
9 min read