4月 24, 2009

【解題】Word Scramble

@
ACM Volume IV 483 - Word Scramble


The Problem

Write a program that will reverse the letters in each of a sequence of words while preserving the order of the words themselves.


Input

The input file will consist of several lines of several words. Words are contiguous stretches of printable characters delimited by white space.


Output

The output will consist of the same lines and words as the input file. However, the letters within each word must be reversed.


Sample Input

I love you.
You love me.
We're a happy family.


Sample Output

I evol .uoy
uoY evol .em
er'eW a yppah .ylimaf


解題思考

  首先,避免麻煩,一開始我們就一次讀入一整行,並存在一個字串中。

  接著,由於要顛倒次序的只有單個單字的字母順序,每個單字還是要依照順序輸出,所以我接著將原始字串以空白字元切割成多個子字串。

  最後,將每一個單字的字母順序顛倒輸出,這一題就完成了。


參考解答(C++)

#include <iostream>
#include <cstring>

#define MAX_SIZE 1024

using namespace std;

int main(void)
{
    char line[MAX_SIZE];
    while (cin.getline(line, MAX_SIZE))
    {
        // 根據空白切割字串
        char *token = strtok(line, " ");
        while (token)
        {
            // 顛倒印出字串
            int length = strlen(token);
            for (int i = length - 1; i >= 0; i--)
            {
                cout << token[i];
            }

            token = strtok(NULL, " ");
            if (token) { cout << " "; }
        }

        cout << endl;
    }

#ifndef ONLINE_JUDGE
    system("pause");
#endif

    return 0;
}

0 回覆:

張貼留言