给定一句英语,要求你编写程序,将句中所有单词的顺序颠倒输出。

输入格式:

测试输入包含一个测试用例,在一行内给出总长度不超过500 000的字符串。字符串由若干单词和若干空格组成,其中单词是由英文字母(大小写有区分)组成的字符串,单词之间用若干个空格分开。

输出格式:

每个测试用例的输出占一行,输出倒序后的句子,并且保证单词间只有1个空格。

输入样例:

  1. Hello World Here I Come

输出样例:

  1. Come I Here World Hello
  1. #include<stdio.h>
  2. #include<string.h>
  3. //最好用入栈出栈做
  4. //耐心做 收获很大
  5. //我太弱了只能用数组 这是精简前的 回忆思路用 精简后的在下面
  6. int main(){
  7. char s[500001];
  8. gets(s);
  9. int len, cpy;
  10. len = strlen(s);
  11. cpy = len;
  12. char c[len];//用c[]实现栈的操作
  13. int i,j,k,count;
  14. int flag=0;
  15. for(i=0; i<len; i++)
  16. c[i] = ' ';//初始化c[]
  17. for(i=0; i<len; i++){
  18. if(s[i]!=' '){
  19. flag = 1;
  20. count++;
  21. }
  22. else{
  23. if(flag==0)
  24. continue;//说明刚才读到的是无意义的连续的空格
  25. else{
  26. for(j=i-count,k=cpy-count;j<i;j++,k++){
  27. c[k] = s[j];
  28. }
  29. count++;//留一个空格
  30. cpy -= count;
  31. count=0;
  32. flag=0;
  33. }
  34. }
  35. }
  36. if(count!=0){//最后一个词没有空格,需要重新写到c[]里
  37. //printf("count=%d", count);
  38. for(j=i-count,k=cpy-count;j<i;j++,k++){
  39. c[k] = s[j];
  40. }
  41. }
  42. flag = 0;
  43. j = 0;
  44. // for(i=j; i<len; i++){
  45. // printf("%c\n", c[i]);
  46. // }
  47. //
  48. while(flag==0){
  49. if(c[j]==' ')
  50. j++;
  51. else
  52. flag=1;
  53. }
  54. for(i=j; i<len; i++){
  55. printf("%c", c[i]);
  56. }
  57. return 0;
  58. }

精简后:

  1. #include<stdio.h>
  2. #include<string.h>
  3. //精简后 删除了多余的flag操作
  4. int main(){
  5. char s[500001];
  6. gets(s);
  7. int len, cpy;
  8. len = strlen(s);
  9. cpy = len;//cpy可以看作用当前c的尾指针位置
  10. char c[len];//用c[]来保存
  11. int i,j,k,count;//count用来记录当前有多少个非空格字符
  12. for(i=0; i<len; i++)
  13. c[i] = ' ';//初始化c[]
  14. for(i=0; i<len; i++){
  15. if(s[i]!=' ')
  16. count++;
  17. else if(count==0)
  18. continue;//说明刚才读到的是无意义的连续的空格
  19. else{//核心思想 最好用纸笔自己演示下
  20. for(j=i-count,k=cpy-count;j<i;j++,k++){
  21. c[k] = s[j];
  22. }
  23. count++;//留一个空格的位置
  24. cpy -= count;
  25. count=0;
  26. }
  27. }
  28. if(count!=0){//最后一个词没有空格,需要重新写到c[]里
  29. for(j=i-count,k=cpy-count;j<i;j++,k++){
  30. c[k] = s[j];
  31. }
  32. }
  33. j = 0;
  34. while(c[j]==' ')//跳过最前面的空格 必不可少的操作
  35. j++;
  36. for(i=j; i<len; i++)
  37. printf("%c", c[i]);
  38. return 0;
  39. }