I am writing a code in C++ to reverse all the words in a string without changing the order of the list
This is my code:
#include<bits/stdc++.h>
using namespace std;
int main()
{
string s = "God Ding";
int n = s.size();
int i = 0, j = 0;
while(j < n){
if(s[j] == ' ' || j == n-1){
reverse(s.begin()+i, s.begin()+j);
j++;
i = j;
}
else{
j++;
}
}
cout << s;
return 0;
}
Expected Output: "doG gniD"
My output: doG Ding
2nd input: "Let's take LeetCode contest"
Expected Output: "s'teL ekat edoCteeL tsetnoc"
My Output: "s'teL ekat edoCteeL contest"
Everything is working fine but only the last word is not getting reversed