Given a string str, the task is to reverse the string by considering each word of the string, str as a single unit.
Input: str = “geeks quiz practice code”
Output: code practice quiz geeks
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:
code practice quiz geeks
Time Complexity: O(N), where N denotes the length of the string.
Auxiliary Space: O(N)
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Check if the given string of words can be formed from words present in the dictionary
- Reverse words in a given String in Java
- Reverse words in a given String in Python
- Program to reverse words in a given string in C++
- Reverse words in a given string
- Print words of a string in reverse order
- Reverse String according to the number of words
- Reverse middle words of a string
- Reverse the Words of a String using Stack
- Count words that appear exactly two times in an array of words
- Reverse individual words
- Reverse individual words with O(1) extra space
- Check if a given string is a Reverse Bitonic String or not
- Count words in a given string
- Program to extract words from a given String
- Check if a two character string can be made using given words
- Shortest substring of a string containing all given words
- Check if given words are present in a string
- Extract and print words separately from a given Camel Case string
- Reverse the substrings of the given String according to the given Array of indices
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.