Simple C++ Iterative O(n) Solution


#1

`string Solution::solve(string s) {
string ans="";
string str="";
int flag=1;

//Iterate sequencially and add non-space characters to str
//and when encounter space and str is not empty then add it ans string
for(int i=0;i<s.length();i++)
{
    if(s[i]==' ' && str!="")
    {
        if(flag)        //Space before first word is not required
        {
            ans=str+ans;
            flag=0;
        }
        else
            ans=str+' '+ans;
            
        str="";
    }
    else if(s[i]!=' ')      // add to str only when non-space character is there
        str+=s[i];
}
//For Last word
if(str!="")
{
    if(ans=="")         //if string 'a' contains only one word
        ans=str+ans;
    else 
        ans=str+' '+ans;
}
return ans;

}`