ZOJ-1151 Word Reversal

Word Reversal

Time Limit: 2 Seconds     Memory Limit: 65536 KB

For each list of words, output a line with each word reversed without changing the order of the words.


This problem contains multiple test cases!

The first line of a multiple input is an integer N, then a blank line followed by N input blocks. Each input block is in the format indicated in the problem description. There is a blank line between input blocks.

The output format consists of N output blocks. There is a blank line between output blocks.


Input

You will be given a number of test cases. The first line contains a positive integer indicating the number of cases to follow. Each case is given on a line containing a list of words separated by one space, and each word contains only uppercase and lowercase letters.


Output

For each test case, print the output on one line.


Sample Input

1

3
I am happy today
To be or not to be
I want to win the practice contest


Sample Output

I ma yppah yadot
oT eb ro ton ot eb
I tnaw ot niw eht ecitcarp tsetnoc


题意概括:输入n行语句,由英文单词和空格构成,将所有的单词反转输出,空格不动。如To反转为oT输出。


解题思路:对输入的语句从头到尾一个循环,如果该位置的字符不是空格存入一个字符串中,遇到空格或回车符时倒着输出字符串中的单词。也可以用栈,非空格入栈,遇到空格栈里内容依次出栈。


代码:


#include<stdio.h>
#include<stack>
using namespace std;
#include<string.h>
int main()
{
	int i,j,k,t,n;
	char str[5010];
	stack<char> s;
	scanf("%d",&t);

	while(t--)
	{	
		scanf("%d",&n);
		getchar();
		for(i=0;i<n;i++)
		{
			memset(str,0,sizeof(str));
			gets(str);
			k=0;
		
			for(j=0;;j++)
			{
				if(str[j]==' '||str[j]=='\0')
				{
					while(!s.empty())
					{
						char s1=s.top();
						printf("%c",s1);
						s.pop();
					}
					if(str[j]==' ')
						printf(" ");
					
				}
				if(str[j]!=' ')
				{
					s.push(str[j]);
				}
				
				if(str[j]=='\0')
					break;	
				
			}
			s.pop();
			printf("\n");
		}
		if(t!=0)
			printf("\n"); 
	}
	return 0;
}

字符串

#include<stdio.h>
#include<string.h>
int main()
{
	int i,j,k,t,n;
	char str[1010][1101],str2[200];
	scanf("%d",&t);

	while(t--)
	{	
		scanf("%d",&n);
		getchar();
		for(i=0;i<n;i++)
		{
			memset(str,0,sizeof(str));
			gets(str[i]);
			k=0;
			//printf("\n");
			for(j=0;;j++)
			{
				if(str[i][j]==' '||str[i][j]=='\0')遇到空格或者回车符时把str2中存的单词倒着输出
                                {
					int l=strlen(str2);
					for(int u=l-1;u>=0;u--)
					{
						printf("%c",str2[u]);
					}
					k=0;
					if(str[i][j]==' ')
						printf(" ");
					memset(str2,0,sizeof(str2));
				}
				if(str[i][j]!=' ')//将单词存入字符串str2中
				{
					str2[k]=str[i][j];
					k++;
				}
				
				if(str[i][j]=='\0')
					break;	
				
			}
			memset(str2,0,sizeof(str2));
			printf("\n");
		}
		if(t!=0)
			printf("\n"); 
	}
	return 0;
}


猜你喜欢

转载自blog.csdn.net/gakki_wpt/article/details/79290806