#54482: C++解答


kita197 (aries)


#include <bits/stdc++.h>
using namespace std;
bool match(const string &S, const string &T) {
    // 特例:沒有 *
    if (S.find('*') == string::npos) {
        return S == T;
    }

    // 拆段
    vector<string> parts;
    string cur;
    for (char c : S) {
        if (c == '*') {
            if (!cur.empty()) {
                parts.push_back(cur);
                cur.clear();
            }
        } else {
            cur.push_back(c);
        }
    }
    if (!cur.empty()) parts.push_back(cur);

    int pos = 0;              // T 中目前可用的位置
    int idx = 0;              // parts index

    // prefix
    if (S[0] != '*') {
        const string &p = parts[0];
        if (T.size() < p.size()) return false;
        if (T.compare(0, p.size(), p) != 0) return false;
        pos = p.size();
        idx = 1;
    }

    // middle parts
    for (; idx < parts.size(); idx++) {
        const string &p = parts[idx];

        // 如果這是最後一段,而且 S 不以 * 結尾 → 留給 suffix 判
        if (idx == parts.size() - 1 && S.back() != '*')
            break;

        auto found = T.find(p, pos);
        if (found == string::npos) return false;
        pos = found + p.size();
    }

    // suffix
    if (S.back() != '*') {
        const string &p = parts.back();
        if (p.size() > T.size()) return false;

        int start = T.size() - p.size();
        // ❗ 必須確保 suffix 在 pos 之後(避免重疊)
        if (start < pos) return false;
        if (T.compare(start, p.size(), p) != 0) return false;
    }

    return true;
}

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    cout.tie(nullptr);
    int N;
    cin >> N;
    cin.get();
    while (N--) {
        string S, T;
        getline(cin,S);
        getline(cin,T);
        if (match(S, T))
            cout << "Yes\n";
        else
            cout << "No\n";
    }
    return 0;
}