Reverse Words in a String

class Solution {
public:
void reverseWords(string &s) {
   string::iterator it;

   int i=0;

   it= s.begin();
  while(it!=s.end() && (*it==' ' || *it=='\t')) {it++;i++;} s=s.substr(i); //跳过开头空格
  if(s=="") return;
 

  reverse(s.begin(),s.end());

  i=0;
  it= s.begin();
  while(it!=s.end() && (*it==' ' || *it=='\t')) {it++;i++;} s=s.substr(i); //跳过结尾空格
  if(s=="") return;

 it= s.begin();

while(it!=s.end())
{
    i=0;
    while(it!=s.end() && (*it==' ' || *it=='\t')) {i++;if(i>1) s.erase(it);else it++; } //跳过空格    这里一定要注意erase之后,it的值啊

    string::iterator it2= it;

    while(it!=s.end() && (*it!=' ' )&& (*it!='\t')) it++;

    reverse(it2,it);
}

}
};

posted @ 2015-07-21 19:05  *桔子*  阅读(119)  评论(0编辑  收藏  举报