BruteForce in O(n) C++


#1

string Solution::solve(string A)
{
string a;
string b;
for(int i=A.length()-1;i>=0;i–)
{

    if(A[i]==' ')
    {
        reverse(b.begin(),b.end());
        a+=b;
        a.push_back(' ');
        b.clear();
    }
    else
    {
        b.push_back(A[i]);
    }
    
}
reverse(b.begin(),b.end());
a+=b;
for(int i=0;i<a.length()-1;i++)
{
    if(a[i]==' ' && a[i+1]==' ')
    {
        a.erase(i,1);
        i=-1;
    }
}
while(a[0]==' ')
{
    a.erase(0,1);
}
while(a[a.length()-1]==' ')
{
    a.erase(a.length()-1,1);
}
return a;

}