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 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|)
Constraints:
1 <= |S| <= 2000
solution:
#include<iostream>
#include<stack>
using namespace std;
string reverseWords(string S)
{
stack<char> s;
string ans;
for (int i = S.length()-1; i >= 0; i--)
{
if (s.empty())
{
s.push(S[i]);
}
else if (!(s.empty()))
{
if (s.top() == '.')
{
s.pop();
while (!(s.empty()))
{
ans += s.top();
s.pop();
}
ans += '.';
}
s.push(S[i]);
}
}
while (s.size())
{
ans += s.top();
s.pop();
}
return ans;
}
int main()
{
string s;
cout << "Enter string: ";
cin >> s;
string result;
result = reverseWords(s);
cout << "result: " << result << "\n";
return 0;
}
No comments:
Post a Comment