现在的位置: 首页 > 综合 > 正文

hdu 1062 Text Reverse 字符串

2013年02月06日 ⁄ 综合 ⁄ 共 1641字 ⁄ 字号 评论关闭

Text Reverse

                                                                                 Time Limit: 2000/1000 MS (Java/Others)    Memory
Limit: 65536/32768 K (Java/Others)

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.
 
题意:输入一个字符串,将字符串中的 单词反转后输出,一次反转一个。
法一:用数组保存单词。
      将不是空格的字符保存在一个数组中,当遇到空格时,将这个数组中的元素从后往前输出。
#include<stdio.h>
#include<string.h>
int main()
{
    int i,n,len,j,k,t;
    char s1[1005],s2[100];
    scanf("%d",&n);
    getchar();
    while(n--)
    {
        gets(s1);
        len=strlen(s1);
        for(i=0,j=0,t=0;i<len;i++)
        {
            if(s1[i]!=' ')
                s2[j++]=s1[i]; /*保存单词*/
            else
            {
                if(t>0) printf(" "); /*控制格式*/
                for(k=j-1;k>=0;k--) 
                    printf("%c",s2[k]); /*反转输出*/
                j=0;
                t++;
            }
            if(i==len-1) /*反转最后一个单词,这里要特别注意*/
            {
                printf(" ");
                for(k=j-1;k>=0;k--)
                    printf("%c",s2[k]);
            }
        }
        printf("\n");
    }
    return 0;
}

法二:用栈。

       单词反转就是把组成这个单词的字母逆序输出,刚好符合栈的“先进后出,后进先出”特性。压栈时,一次压入一个字符。
#include<stdio.h>
#include<stack>
using namespace std;
int main()
{
	int n;
    char ch;
	scanf("%d",&n);
	getchar(); /*吸收回车符*/
	while(n--)
	{
		stack<char> s; /*定义栈*/
		while(true)
		{
			ch=getchar(); /*压栈时,一次压入一个字符*/
            if(ch==' '||ch=='\n'||ch==EOF)
			{
				while(!s.empty())
				{
					printf("%c",s.top()); 
					s.pop(); /*清除栈顶元素*/
				}
				if(ch=='\n'||ch==EOF)  
					break;  /*绝对不能少,控制输出结束*/
				printf(" ");
			}
			else
				s.push(ch);
		}
		printf("\n");
	}
	return 0;
}

抱歉!评论已关闭.