language: C
char* reverseWords(char* s){
int i,p,j;
// 先算长度
int getlen(char *st){
int count = 0;
while(st[count] != ' ')
count++;
return count;
}
int len = getlen(s);
if(len ==0)
return "";
// 翻转的函数,
void inverse(char *st, int start, int end){
char temp;
while(start<end){
temp = st[start];
st[start] = st[end];
st[end] = temp;
start++;
end--;
}
}
// 为 去除多余的空格 做的准备
p = 0; //从此开始p 用来记录空格的数量,最后去尾end = len-1-p
void deleteonechar(char *st, int position,int end){
for(;position<end;position++){
st[position] = st[position+1];
}
p++;
}
// 去头空格
i = 0;
while((i<len-p)&&(s[i] ==' '))
i++;
for(j=0;j<i;j++)
deleteonechar(s,0,len-1-p);
// 全翻转一次
inverse(s,0,len-1-p);
// 把每个单词翻转一次,
int m=0;
bool i_filled =false;
while(m<len-p){
if(i_filled){ // 找j
if(s[m]==' '){
inverse(s,i,m-1);
i_filled = false;
}
}else{
if(s[m] !=' '){
i = m;
i_filled = true;
}
}
m++;
}
inverse(s,i,m-1);
i = 0;
// 先找不为空格的第一个字符
while((i<len-p)&&(s[i] ==' '))
i++;
for(j=0;j<i;j++)
deleteonechar(s,0,len-1-p);
// 接下来去除所有单词中间的多余的空格
i = 0;
while(i<len-p){
if((i-1>=0)&&(s[i-1] == ' ')&&(s[i] == ' ')){
deleteonechar(s,i,len-1-p);
i--;
}
i++;
}
if(p!=0)
s[len-p] = ' ';
return s;
}