Given an input string, reverse the string word by word.
For example,
Given s = "the sky is blue
",
return "blue is sky the
".
Update (2015-02-12):
For C programmers: Try to solve it in-place in O(1) space.
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.
分析:
先去除多余的空格,再做两次reverse。
class Solution {
public:
void reverseWords(string &s) {
for(int i=0;i<s.size();)
{
if(s[i]==' '&&(i==0||i==s.size()-1||s[i+1]==' '))
s.erase(i,1);
else i++;
}
int n=s.size();
if(n==0) return;
reverse(s.begin(),s.end());
for(int i=0;i<s.size();)
{
int j=i+1;
while(j<n&&s[j]!=' ') j++;
reverse(next(s.begin(),i),next(s.begin(),j));
i=j+1;
}
}
};