给定一句英语,要求你编写程序,将句中所有单词的顺序颠倒输出。
输入格式:
测试输入包含一个测试用例,在一行内给出总长度不超过500 000的字符串。字符串由若干单词和若干空格组成,其中单词是由英文字母(大小写有区分)组成的字符串,单词之间用若干个空格分开。
输出格式:
每个测试用例的输出占一行,输出倒序后的句子,并且保证单词间只有1个空格。
输入样例:
Hello World Here I Come
输出样例:
Come I Here World Hello
#include<stdio.h>
#include<string.h>
//最好用入栈出栈做
//耐心做 收获很大
//我太弱了只能用数组 这是精简前的 回忆思路用 精简后的在下面
int main(){
char s[500001];
gets(s);
int len, cpy;
len = strlen(s);
cpy = len;
char c[len];//用c[]实现栈的操作
int i,j,k,count;
int flag=0;
for(i=0; i<len; i++)
c[i] = ' ';//初始化c[]
for(i=0; i<len; i++){
if(s[i]!=' '){
flag = 1;
count++;
}
else{
if(flag==0)
continue;//说明刚才读到的是无意义的连续的空格
else{
for(j=i-count,k=cpy-count;j<i;j++,k++){
c[k] = s[j];
}
count++;//留一个空格
cpy -= count;
count=0;
flag=0;
}
}
}
if(count!=0){//最后一个词没有空格,需要重新写到c[]里
//printf("count=%d", count);
for(j=i-count,k=cpy-count;j<i;j++,k++){
c[k] = s[j];
}
}
flag = 0;
j = 0;
// for(i=j; i<len; i++){
// printf("%c\n", c[i]);
// }
//
while(flag==0){
if(c[j]==' ')
j++;
else
flag=1;
}
for(i=j; i<len; i++){
printf("%c", c[i]);
}
return 0;
}
精简后:
#include<stdio.h>
#include<string.h>
//精简后 删除了多余的flag操作
int main(){
char s[500001];
gets(s);
int len, cpy;
len = strlen(s);
cpy = len;//cpy可以看作用当前c的尾指针位置
char c[len];//用c[]来保存
int i,j,k,count;//count用来记录当前有多少个非空格字符
for(i=0; i<len; i++)
c[i] = ' ';//初始化c[]
for(i=0; i<len; i++){
if(s[i]!=' ')
count++;
else if(count==0)
continue;//说明刚才读到的是无意义的连续的空格
else{//核心思想 最好用纸笔自己演示下
for(j=i-count,k=cpy-count;j<i;j++,k++){
c[k] = s[j];
}
count++;//留一个空格的位置
cpy -= count;
count=0;
}
}
if(count!=0){//最后一个词没有空格,需要重新写到c[]里
for(j=i-count,k=cpy-count;j<i;j++,k++){
c[k] = s[j];
}
}
j = 0;
while(c[j]==' ')//跳过最前面的空格 必不可少的操作
j++;
for(i=j; i<len; i++)
printf("%c", c[i]);
return 0;
}