Given an input string, reverse the string word by word.
For example,
Given s = "the sky is blue
",
return "blue is sky the
".
- 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
class Solution {
public:
void reverseWords(string &s) {
stack<string> strstack;
int start = 0;
int length = s.length();
string str;
while ( (start < length) && (s.at(start) == ' ')) //去掉头部的空格
{
start++;
}
for (int i = start; i < length; )
{
if (s.at(i) != ' ')
{
i++;
}
else
{
str = s.substr(start,i-start);
strstack.push(str);
while ( (i < length) && (s.at(i) == ' '))//去掉单词之间的多个空格
{
i++;
}
start = i;
}
}
if (length != start)//防止尾部出现空格
{
strstack.push(s.substr(start,length-start));
}
s = "";
while (!strstack.empty())
{
s = s+ strstack.top();
strstack.pop();
if (!strstack.empty())
{
s = s + " ";
}
}
}
};