Reverse Words in a String

来源:互联网 发布:js input禁止输入空格 编辑:程序博客网 时间:2024/05/16 08:41

Given an input string, reverse the string word by word.

For example,
Given s = "the sky is blue",

return "blue is sky the".


------------------------------------

再次写这代码写的各种乱

需要考虑到字符串的空格~!写的时候还是需要理清了思路再写 ~

class Solution {public:    void reverseWords(string &s) {                       s.erase(0,s.find_first_not_of(" "));          s.erase(s.find_last_not_of(" ") + 1);if(s.length()<1)return ;if(s.length()==1 && strcmp(s.c_str()," ")!=0){return;} int flag=0;int n=s.length();       int i=0;   while(i<n/2){swap(s[i],s[n-1-i]);i++;}   for( i=0;i<n;)   {   int j=i;   while(j<n && s[j]!=' ')   {   j++;   }   int t=i;   int e=j;   while(t<(i+j)/2 )   {   swap(s[t],s[e-1]);   e--;   t++;   }   i=j+1;   }   string ::iterator it=s.begin();   int ss=0;   while(ss<s.size())   {   while(ss<s.size() && s[ss]!=' ')   ss++;   if(ss< s.size() && s[ss]==' ')   {   int jj=ss+1;   while(jj<s.size() && s[jj]==' ')   jj++;   s.erase(ss+1,jj-ss-1);   ss=ss+1;   }   }    }};


0 0
原创粉丝点击