Given an input string, reverse the string word by word.
For example,
Given s = "the sky is blue
",
return "blue is sky the
".
Clarification:
- What constitutes a word?
A sequence of non-space characters constitutes a word. - Could the input string contain leading or trailing spaces?
Yes. However, your reversed string should not contain leading or trailing spaces. - How about multiple spaces between two words?
- Reduce them to a single space in the reversed string.
思路:转到vector中逆向输出
c++代码:
//Reverse Words in a String
#include<algorithm>
#include<string>
#include<iostream>
#include<vector>
using namespace std;
class Solution {
public:
void reverseWords(string &s) {
vector<string> vstr;
string tmp;
tmp.clear();
for(string::iterator it=s.begin(); it!=s.end(); ++it)
{
if(*it!=' ')
{
tmp += *it;
if((it+1)==s.end() || (*(it+1)==' '))
{
vstr.push_back(tmp);
tmp.clear();
}
}
}
s.clear();
reverse(vstr.begin(),vstr.end());
for(vector<string>::iterator it=vstr.begin();
it!=vstr.end();++it)
{
if(it!=vstr.begin())
s+=" ";
s+= *it;
}
}
};
int
main(void)
{
string s;
getline(cin,s);
Solution sn;
sn.reverseWords(s);
cout<<s;
return 0;
}