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
思路: 從前往後把單詞摳出來,然後把單詞從後往前拼接.亦可以用兩次逆序的方法
class Solution
{
public:
void reverseWords(string &s)
{
vector <string> words;//保存摳出的單詞
bool flag = 0;
string w;
for(int i = 0; i != s.size(); i++)
{
if(s[i] != ' ')
{
if(flag == 0) flag = 1;
w.push_back(s[i]);
}
else
{
if(flag == 1)
{
words.push_back(w);
w.clear();
flag = 0;
}
}
}
if(flag == 1) words.push_back(w);//最後一個可能沒遇到空格就結束了
s.clear();
if(words.size())//排除只有空格的字符串或者空字符串
{
for(int i = words.size() - 1; i != 0; i--)
{
s = s + words[i] + ' ';
}
s = s + words[0];
}
}
};