一、题目要求
Given an input string, reverse the string word by word.
For example,
Given s = "the sky is blue",
return "blue is sky the".
二、代码实现
void reverseWords(string &s) {
if(s.empty())
return;
bool flag=true;
s.erase(0,s.find_first_not_of(" "));
s.erase(s.find_last_not_of(" ")+1);
if(s.empty())
{
return;
}
size_t pos,count=0;
for(auto tmp=0;tmp<s.size();tmp++)
{
if(s[tmp]==' ')
{
if(!flag)
{
s=s.erase(tmp,1);
tmp--;
}
else
flag=false;
}
else if(s[tmp]!=' ')
{
flag=true;
}
}
//cout<<"==="<<s<<endl;
stringstream ss(s);
vector<string> v;
string word;
while(ss>>word)
{
v.push_back(word);
}
ss.clear();
stack<string,vector<string>> st(v);
while(st.size()>1)
{
//cout<<st.top()<<endl;
ss<<st.top()<<" ";
st.pop();
}
ss<<st.top();
s=ss.str();
ss.clear();
}