Reverse Words in a String Total
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?
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];
}
}
};