Cpp | O(n) solution


#1

string Solution::solve(string A) {
string ans="";
int n=A.length();
string word="";
for(int i=n-1; i>=0; i–){
if(A[i]==’ ‘){
if(word!="")
ans+=word+" “;
word=”";
}
else{
word=A[i]+word;
}
}
ans+=word;
if(ans[ans.length()-1]==’ '){
ans=ans.substr(0, ans.length()-1);
}
return ans;
}


#2

Kind of similar but smaller code

            int i=0,n=a.length();
        string ans;
        while(i<n){
            while(i<n && a[i]==' ') i++;
            string tmp="";
            while(i<n && a[i]!=' '){
                tmp.push_back(a[i]);
                i++;
            }
            if(tmp.length()>0)
            ans=tmp+" "+ans;
        }
        ans.erase(ans.end()-1);
        return ans;