Reversing Words

String Manipulation Example

Sukanya Bharati
TheLeanProgrammer
2 min readSep 22, 2021

--

Given a String S, reverse the string without reversing its individual words. Words are separated by dots.

Example 1:

Input:
S = i.like.this.program.very.much
Output: much.very.program.this.like.i
Explanation:
After reversing the whole
string(not individual words), the input
string becomes
much.very.program.this.like.i

Example 2:

Input:
S = pqr.mno
Output: mno.pqr
Explanation:
After reversing the whole
string , the input string becomes
mno.pqr

Your Task:
You don't need to read input or print anything. Complete the function reverseWords() which takes string S as input parameter and returns a string containing the words in reversed order. Each word in the returning string should also be separated by ‘.’

Expected Time Complexity: O(|S|)
Expected Auxiliary Space: O(|S|)

Constraints:
1 <= |S| <= 2000

Approach :

  1. Having O(|s|) space complexity & O(|s|) time complexity where |s| is the length of the given string

class Solution
{
public:
//Function to reverse words in a given string.
string reverseWords(string s)
{
string str="";
string result = "";
string word;

1 for(int i=0;s[i]!='\0';i++)
{
2 if(s[i]=='.')
{
3 word = s[i]+str;
4 str="";
}
5 else
{
6 str+=s[i];
}
7 result = word+result;
8 word="";
}
9 if(str!="")
10 result = str+result;
11 return result;
}
};
Below I will dry run an input to help you understand better.
You can infer from the above code using the numbers which have been marked and can easily understand how this question has been solved.

I am simply adding the dots before the word, like for eg above I made the word as .pqr and then appended it with the later word. So using this logic it becomes easy to get the desired output.

Link for the question: https://practice.geeksforgeeks.org/problems/reverse-words-in-a-given-string5459/1#

Hope it helps! Keep coding!

Since you enjoyed reading my blog , why not buy me a coffee and supoort my work here!! https://www.buymeacoffee.com/sukanyabharati

Don’t forget to follow The Lean Programmer Publication for more such articles, and subscribe to our newsletter tinyletter.com/TheLeanProgrammer

--

--

Sukanya Bharati
TheLeanProgrammer

A happy , motivated & a curious soul if you end up finding me 😎😁.