Easy to understand cpp solution


#1
string Solution::solve(string A) {
string res = "";
stack<string> st;
for(int i=0;i<A.size();i++)
{
    if(A[i] != ' ')res += A[i];
    else if(A[i] == ' ' || i == A.size() - 1)
    {
        st.push(res);
        res = "";
    }
    
}
st.push(res);
A="";
while(!st.empty())
{
    A += st.top() + " ";
    st.pop();
}

return A.substr(0,A.size()-1);

}


#2

How are you handling the mutiple spaces between words.


#3
else if(A[i] == ' ' || i == A.size() - 1)
{
    st.push(res);
    res = "";
}

the above part handles the multiple spaces. If the first space is encountered the whole res string is added and converted to null string, now when second space is encountered res (which is null string) is added to the result string. So we are just adding an empty string which does not makes any difference.


#4

The solution provided above is wrong.

Reason : Everytime you pop an empty string from the stack, a space gets added to the output string which shouldn’t have been the case.

This can be overcomed by putting a simple check as in the code below :

string Solution::solve(string A) {
string res = “”;
stack st;
for(int i=0;i<A.size();i++)
{
if(A[i] != ’ ')res += A[i];
else if(A[i] == ’ ’ || i == A.size() - 1)
{
st.push(res);
res = “”;
}

}
st.push(res);
A="";
while(!st.empty())
{
string t=st.top();
if(t!="")
A += st.top() + " ";
st.pop();
}

return A.substr(0,A.size()-1);
}