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.
字符串反转的问题,有很多种方法。但本题要求删除多余的空格,所以比较特别,最直接的方法就是把所有单词取出来放到栈当中,再弹出。但题目要求不能用多余的辅助空间,所以只能在翻的时候去掉多余的空格。
class Solution { public: void reverseWords(string &s) { reverse(s.begin(),s.end());
//首先去除头尾的空格 while(*(s.begin())==' ') { s.erase(s.begin()); } while(*(s.end()-1)==' ') { s.erase(s.end()-1); } string::iterator iter1=s.begin(); string::iterator iter2=s.begin(); for(;iter2!=s.end();++iter2) { if(*iter2==' ' && *iter1!=' ') {//反转每一个单词 reverse(iter1,iter2); iter1=iter2+1; } else if(*iter2==' ' && *iter1==' ') {//去除中间的空格 iter1--; s.erase(iter2); iter2=iter1; iter1++; } } reverse(iter1,s.end());//最后一个单词 } };