杭電ACM 1062

廢話不說,先上題:數組

Text Reverse

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 17744    Accepted Submission(s): 6730


測試

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
3 olleh !dlrow m'I morf .udh I 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.
 
 
這道題初看感受不難,可是提交的時候   各類報PE錯誤  擦  無奈了
通過N次測試後  發現測試數據  各類數據之間有多個空格,數據起始可能有多個空格   基本解決好這兩個問題就能提交了
先上未優化前的代碼:
#include <stdio.h>
#include <string.h>
char a[1002];
void print(char *q)
{
	while((q+1)!=a)
    {
    	printf("%c", *q--);
    	if (*q==' ') {break;}
    }
}
int main()
{
    int n,i;
    char *p;
    while(scanf("%d",&n)!=EOF)
    {
    	getchar();
    	while(n--){ 
    	    memset(a,'\0',sizeof(a));
	    	gets(a); p=a;
	    	while(*p==' '){putchar(' ');p++;};
	    	while(1)
	    	{
	    		while(*p!=' ')
	    		{ 
	    			if(*(p+1)=='\0'){print(p);break;}
	    			if (*(p+1)==' ') {print(p);putchar(' ');break;}
	    			p++; 
	    		}p++; p++;
	    		if(*p=='\0')break;
	    		else while(*p==' '){putchar(' ');p++;};
	    	}
	    	putchar('\n');
	    }
   	}
   	return 0;
}

 還有用數組的:優化

#include <stdio.h>
int main()
{
	int n,i,j,k;
	char array[1001],t;
	while(scanf("%d",&n)!=EOF)
	{
		getchar();
		while(n--)
		{
			i=0;
			gets(array);
			while(array[i]!='\0')
			{
				if(array[i]==' ') { i++;continue; }
				j=i;
				while((array[j+1]!=' ')&&(array[j+1]!='\0')) j++;
				k=j;
				while(i<j)
				{
					t=array[i]; array[i]=array[j]; array[j]=t;i++;j--; 
				}
				i=k+1;
			}
			puts(array);
		}
	}
	return 0;
}
相關文章
相關標籤/搜索