字符串逆序输出

xiaoxiao2021-02-28  109

字符串逆序输出

时间限制: 3000 ms  |  内存限制: 65535 KB 难度: 0 描述 给定一行字符,逆序输出此行(空格.数字不输出) 输入 第一行是一个整数N(N<10)表示测试数据的组数) 每组测试数据占一行,每行数据中间有且只有一个空格(这样你可以把此行当成两个字符串读取)。 每行字符长度不超过40 并且保证输入的字符只有空格(1个),数字,小写字母三种 输出 对应每行测试数据,逆序输出(空格和数字不输出) 样例输入 3 abc 123de abc 123 abc d 样例输出 edcba cba dcba 来源 [521521]原创 上传者 ACM_赵铭浩

代码:

#include <iostream> #include <stdio.h> #include <string.h> #include <math.h> #include <vector> #include <queue> #include <stack> #include <map> #include <string> #include <algorithm> using namespace std; /* run this program using the console pauser or add your own getch, system("pause") or input loop */ int main(int argc, char** argv) { int n; scanf("%d",&n); getchar(); while(n--){ char input[41]; gets(input); //cout<<input<<endl; int length=strlen(input); for(int i=length-1;i>=0;i--){ if(input[i]>='a' && input[i]<='z'){ printf("%c",input[i]); } } printf("\n"); } return 0; }优秀代码:

01. #include <stdio.h> 02. void revers() 03. { 04. char c; 05. if((c = getchar()) != '\n') 06. revers(); 07. if(c != '\n'&&c>='a'&&c<='z') 08. putchar(c); 09. } 10.   11. int main() 12. { 13. int a; 14. scanf("%d\n",&a); 15. while(a--) 16. { 17. revers(); 18. printf("\n"); 19. } 20. return 0; 21. } 代码对比分析:

我的代码是先把一行都读入字符数组中,然后再倒序遍历字符数组,根据限制条件进行输出。

优秀代码就比较奇怪,用了递归函数,每次只读一个字符,利用递归函数内部实现的栈暂时存储读入的字符,最后遇到换行符时,递归回上层进行依次输出,实现了倒序。好处是不用自己申请空间,但递归函数应该是比较费时的。

收获:

利用递归函数来实现数据的存储,可以。

转载请注明原文地址: https://www.6miu.com/read-74236.html

最新回复(0)