ZOJ1151 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

Source: East Central North America 1999, Practice

问题链接ZOJ1151 Word Reversal
问题简述:(略)
问题分析
    这是一个简单的文本处理问题。用C++实现的话,可以使用字符串留来处理。正道还是用字符流和堆栈来解决。
程序说明:(略)
参考链接:(略)
题记:(略)

AC的C语言程序如下:

/* ZOJ1151 Word Reversal */

#include <stdio.h>

#define MAXSTACK 1024

char stack[MAXSTACK];
int pstack;

void push(char c)
{
    stack[pstack++] = c;
}

char pop()
{
    return stack[--pstack];
}

int main(void)
{
    int t, line, i;
    char c;

    scanf("%d", &t);
    while(t--) {
        scanf("%d", &line);
        getchar();

        pstack = 0;

        for(i=1; i<=line; i++) {
            c = getchar();
            while(c != '\n') {
                if(c == ' ') {
                    while(pstack)
                        putchar(pop());
                    putchar(c);
                } else
                    push(c);
                c = getchar();
            }

            while(pstack)
                putchar(pop());
            putchar('\n');
        }

        if(t) putchar('\n');
    }

    return 0;
}

AC的C++语言程序如下:

/* ZOJ1151 Word Reversal */

#include <iostream>
#include <string>
#include <sstream>

using namespace std;

void reverse(string& s)
{
    string t;
    stringstream ss(s);
    bool flag = false;
    while(ss >> t) {
        if(flag) cout << ' ';
        flag = true;
        for(int i = (int)t.size() - 1; i >= 0; i--)
            cout << t[i];
    }
    cout << endl;
}

int main()
{
    int t, n;
    cin >> t;
    while(t--) {
        cin >> n;
        cin.get();
        string s;
        for(int i = 1; i <= n; i++) {
            getline(cin, s);
            reverse(s);
        }
        if(t) cout << endl;
    }

    return 0;
}

猜你喜欢

转载自www.cnblogs.com/tigerisland45/p/10269587.html