a719簡單鍵盤列的位置映射

CPE:Decode the Mad man (UVa 10222)

建立向左兩格的查表轉換並保留空白。

前往題目練習 →回報教學錯誤時間 O(L),固定大小查表空間 O(1)。

解題思路

鍵盤位置並非字母順序,應直接列出四列按鍵。對每列索引 i≥2 的字元,記錄它解碼為索引 i−2 的字元,避免在不同列之間錯誤跨越。

把輸入英文字母先轉成小寫,再逐字查表,空白原樣保留。列首兩個按鍵沒有左邊兩格,若遇到未建立映射的字元便原樣保留;合法編碼應只使用可解碼位置。讀入整段訊息,輸出解碼行。

Step-by-step animation

示意:k[r → how

回報動畫錯誤
步驟 1 / 3

解 k

asdfghjkl 列中 k 的左兩格是 h。

h
j
k
輸出長度
1
文字
h

Reference solution

回報程式錯誤

完整程式

#include <iostream>
#include <string>
#include <cctype>
using namespace std;
int main() {
    string rows[] = {"\x60"
                     "1234567890-=",
                     "qwertyuiop[]\\", "asdfghjkl;'", "zxcvbnm,./"};
    char table[256];
    for (int i = 0; i < 256; ++i)
        table[i] = char(i);
    for (auto &r : rows)
        for (size_t i = 2; i < r.size(); ++i)
            table[(unsigned char)r[i]] = r[i - 2];
    string s;
    while (getline(cin, s)) {
        if (!s.empty() && s.back() == '\r')
            s.pop_back();
        for (unsigned char c : s)
            cout << table[tolower(c)];
        cout << '\n';
    }
}

先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。

更多