a624簡單有優先序的字尾規則

CPE:Deli Deli (UVa 11233)

以互斥條件依序套用英文複數轉換規則。

前往題目練習 →回報教學錯誤每字 O(Len),字典儲存 O(L·Len)。

解題思路

先把 L 組不規則對應存成字典,這一層優先於任何字尾規則。若查不到,再檢查字尾是否為 y 且前一字母是子音;只有這種情況把 y 換成 ies,像 turkey 的前一字母是 e,應直接加 s。

其餘再判定 o、s、ch、sh、x 字尾,符合時加 es,最後才是一般加 s。條件必須以 if/else 串接,避免一次套用多條。讀 L、N 後精確處理 N 個單字;長度為 1 的 y 沒有前字母,不可越界讀取。

Step-by-step animation

示意:city、toy、box

回報動畫錯誤
步驟 1 / 3

city

y 前是子音 t,移除 y 後加 ies。

cit
y
ies
輸出
cities
新長度
6

Reference solution

回報程式錯誤

完整程式

#include <iostream>
#include <map>
#include <string>
using namespace std;
bool ends(const string &s, const string &tail) {
    return s.size() >= tail.size() && s.compare(s.size() - tail.size(), tail.size(), tail) == 0;
}
int main() {
    int l, n;
    cin >> l >> n;
    map<string, string> irregular;
    string a, b;
    while (l--) {
        cin >> a >> b;
        irregular[a] = b;
    }
    while (n--) {
        cin >> a;
        if (irregular.count(a))
            b = irregular[a];
        else if (a.size() > 1 && a.back() == 'y' &&
                 string("aeiou").find(a[a.size() - 2]) == string::npos)
            b = a.substr(0, a.size() - 1) + "ies";
        else if (ends(a, "o") || ends(a, "s") || ends(a, "ch") || ends(a, "sh") || ends(a, "x"))
            b = a + "es";
        else
            b = a + "s";
        cout << b << '\n';
    }
}

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

更多