class Solution {
public:
void reverseWords(string &s) {
istringstream record(s);
string temp;
vector<string> vec;
while(record>>temp)
{
vec.push_back(temp);
}
int theSize=vec.size();
s="";
for(auto i=theSize-1;i>=0;i--)
{
s=s+vec[i];
if(i!=0)
s=s+" ";
}
}
};
不使用vector,直接使用istringstream来解决
/**
* 1.s is empty.
* 2.s is spaces.
* 3.s ends or begins with spaces.
*/
class Solution {
public:
void reverseWords(string &s) {
if(s.empty())
return;
istringstream record(s);
string str;
s.clear();
while(record>>str)
{
s=str+' '+s;
}
if(!s.empty())
s.erase(s.end()-1);
}
};