hdu 1062Text Reverse 反转字符串【两种方法 数组法、堆栈】

来源:互联网 发布:上海ug编程培训班 编辑:程序博客网 时间:2024/05/18 01:31
Problem Description
Ignatius likes to write words in reverse way. Given a single line of text which is written by Ignatius, you should reverse all the words and then output them.
 

Input
The input contains several test cases. The first line of the input is a single integer T which is the number of test cases. T test cases follow.
Each test case contains a single line with several words. There will be at most 1000 characters in a line.
 

Output
For each test case, you should output the text which is processed.
 

Sample Input
3olleh !dlrowm'I morf .udhI ekil .mca
 

Sample Output
hello world!I'm from hdu.I like acm.
Hint
Remember to use getchar() to read '\n' after the interger T, then you may use gets() to read a line and process it.
#include<stdio.h>#include<string.h>#include<stdlib.h>#include<math.h>#include<ctype.h>int main(){char str1[1000],str2[1000]={0};int T,i,t,len,j,k;scanf("%d",&T);getchar();   //因为是用的gets,所以要把回车处理 while(T--){gets(str1);len=strlen(str1);   //这里不可以放在while外面,因为并没有读入str1,所以len并没有值 t=0;j=0;for(i=0;i<len;i++){if(str1[i]!=' ')   //要用单引号 而不是双引号 str2[j++]=str1[i];else               //遇到空格的情况    {if(t>0)printf(" ");for(k=j-1;k>=0;k--){printf("%c",str2[k]);}j=0;t++;   } if(i==len-1)    //此为反转最后一个字符串,先输出空格,因为若只有两个单词,并不执行第二个else,因为最后并不是空格 {printf(" ");for(k=j-1;k>=0;k--)printf("%c",str2[k]); }}printf("\n");}return 0;}



#include<stdio.h>#include<stack>using namespace std;int main(){char ch;int i,T;scanf("%d",&T);getchar();while(T--){stack<char> str;while(true){ch=getchar();if(ch==' '||ch=='\n'||ch==EOF){while(!str.empty()){printf("%c",str.top());  //出栈顶元素 str.pop();   //清空栈顶元素 } if(ch=='\n'||ch==EOF)break;  //结束的标志 printf(" ");} elsestr.push(ch);}printf("\n");}return 0;}




0 0
原创粉丝点击