8月 04, 2008

【解題】WERTYU

@
ACM Volume C 10082 - WERTYU


The Problem

A common typing error is to place the hands on the keyboard one row to the right of the correct position. So "Q" is typed as "W" and "J" is typed as "K" and so on. You are to decode a message typed in this manner.


The Input

Input consists of several lines of text. Each line may contain digits, spaces, upper case letters (except Q, A, Z), or punctuation shown above [except back-quote (`)]. Keys labelled with words [Tab, BackSp, Control, etc.] are not represented in the input.


The Output

You are to replace each letter or punction symbol by the one immediately to its left on the QWERTY keyboard shown above. Spaces in the input should be echoed in the output.


Sample Input

O S, GOMR YPFSU/


Sample Output

I AM FINE TODAY.


解題思考

  `1234567890-=QWERTYUIOP[]\ASDFGHJKL;'ZXCVBNM,./

  以上不是亂碼。

  除了空白或是換行,在讀入每一個字元之後,我們需要搜尋利用以上元素建立的陣列,找到其對應的索引值(index)之後,輸出其前一個索引值的字元。

  這樣,就達成題目的要求了。


參考解答(C++)

#include <iostream>

using namespace std;

// 定義對應表字元陣列
const char word[] = {'`', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '-', '=',
                    'Q', 'W', 'E', 'R', 'T', 'Y', 'U', 'I', 'O', 'P', '[', ']', '\\',
                    'A', 'S', 'D', 'F', 'G', 'H', 'J', 'K', 'L', ';', '\'',
                    'Z', 'X', 'C', 'V', 'B', 'N', 'M', ',', '.', '/'};

int main(void)
{
    char c;
    while (cin.get(c))
    {
        // 假如是空白或換行就直接輸出
        if (c == ' ')       { cout << c; }
        else if (c == '\n') { cout << endl; }
        else
        {
            // 搜尋輸入字元, 輸出其前一個字元
            for (int i = 0; i < 47; i++)
            {
                if (word[i] == c)
                {
                    cout << word[i - 1];
                    break;
                }
            }
        }
    }

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

2 回覆:

kgame 智涵 提到...

我直接把字元當索引查詢陣列
時間複雜度可達O(1)
只是陣列中會有不少垃圾元素

Unknown 提到...

雖然會浪費空間, 但是也不失為一種好方法:)

張貼留言