Reverse words in a given string
Problem Statement - link #
Given a String S
, reverse the string without reversing its individual words. Words are separated by dots.
Your Task: You dont 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|)
Examples #
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
Constraints #
1 <=|S|≤ 2000
Solutions #
class Solution{
public:
//Function to reverse words in a given string.
string reverseWords(string S)
{
// code here
int i = 0, j = 0;
while( i < S.size()){
while( j < S.size() && S[j]!='.') j++;
reverse(S.begin()+i, S.begin()+j);
i = j + 1;
j = i;
}
reverse(S.begin(), S.end());
return S;
}
};