Simple iterative C++ solution with comment


#1

string a = “”;
int n = A.size();
string res = “”;

for(int i=n-1;i>=0;i--)
{
    if(A[i] != ' ')
        a += A[i];
    else
    {

//Add only if ‘a’ contain word
if(a.length() != 0)
{
reverse(a.begin(),a.end());
res += a;
res+= " ";
a = “”;
}
}
}

reverse(a.begin(),a.end());
res += a;

// Now removing space from starting and ending point of string
int i = 0;
while(res[i] == ’ ')
++i;
string ans = “”;
int j = res.length()-1;
while(res[j] == ’ ')
–j;

//cout<<i<<" "<<j;

for(i;i<=j;i++)
    ans+=res[i];

return ans;