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;
}
}
}
};