问题描述:
Given an input string, reverse the string word by word.
For example,
Given s = "the sky is blue
",
return "blue is sky the
".
之前就做过一遍,没想到再做的时候虽然有思路但是还是有很多问题,看来刷一遍是不够的,刷完在刷一遍
上代码
class Solution {
public:
void reverseWords(string &s) {
vector<string> str;
if(s=="")
return;
int i=0;
while(s[i]==' ')
i++;
string strTemp = "";
for(;i<s.length();i++)
{
if(s[i]!=' ')
strTemp+=s[i];
else
{
if(strTemp!="")
str.push_back(strTemp);
strTemp="";
}
}
if(strTemp!="")
str.push_back(strTemp);
if(str.size()==0)
s="";
else
{
s=str[str.size()-1];
for(int i=str.size()-2;i>=0;i--)
s=s+" "+str[i];
}
}
};