Word Reversal

Word Reversal

时间: 1ms        内存:64M

描述:

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

输入:

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.

输出:

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

示例输入:

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

示例输出:

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

提示:

参考答案(内存最优[752]):

#include<stdio.h>
int main()
{int n,i,j,k,m,x;
 char a[100];
 scanf("%d",&n);
 getchar();
 for(i=1;i<=n;i++)
 {   m=0;
     gets(a);
     for(j=0;;j++)
     {   m++;
	 if(a[j]==' '||a[j]=='\0')
	 {  x=j;
	    for(k=0;k<m-1;k++)
	    {   printf("%c",a[x-1]);
		x--;
	    }
	    m=0;
	    if(a[j]!='\0')
	       printf("%c",a[j]);
	 }
	 if(a[j]=='\0')
	    break;
     }
     printf("\n");
 }
 return 0;
}

参考答案(时间最优[4]):

#include <stdio.h>
#include <string.h>
const int maxn = 100005;
char str[maxn], stack[maxn];
int is_letter ( char ch )
{
    return (ch >= 'A' && ch <= 'Z' )|| (ch >= 'a' && ch <= 'z');
}
int main ( )
{
    int  n,len;
    scanf ( "%d%*c", &n );
    while (n --)
    {
        int top = -1;
        fgets ( str, maxn, stdin );
        len = strlen ( str );
        for ( int i = 0; i < len; i ++ )
        {
            if ( is_letter ( str[i] ) )
                stack[++ top] = str[i];
            else
            {
                while ( top >= 0 )
                    printf ( "%c", stack[top --] );
                printf ( "%c", str[i] );
            }
        }
        while ( top >= 0 )
            printf ( "%c", stack[top --] );
    }
    return 0;
}

题目和答案均来自于互联网,仅供参考,如有问题请联系管理员修改或删除。

点赞

发表评论

电子邮件地址不会被公开。必填项已用 * 标注