【題解】ZeroJudge c146: 105北二4找尋子字串

【題目敘述】https://zerojudge.tw/ShowProblem?problemid=c146

#include <iostream>
using namespace std;

int n, ans, cnt;
string s, t;

int main() {
    cin >> t >> s;
    cin >> n;
    for (int j = s.length(); j >= t.length(); j--){
        for (int l = 0; l < s.length(); l++){
            if (s[l] != t[0]) continue;
            int r = l+j-1;
            if (r >= s.length() || s[r] != t[t.length()-1]) continue;
            int p = l;
            bool flag = true;
            for (int i = 0; i < t.length(); i++){
                while (p <= r && s[p] != t[i]) p++;
                if (p > r){
                    flag = false;
                    break;
                }
                p++;
            }
            if (flag){
                ans += r-l+1;
                //cout << l << " " << r << "\n";
                cnt++;
                if (cnt == n){
                    cout << ans << "\n";
                    return 0;
                }
            }
        }
    }
    cout << ans << "\n";
}
分享本文 Share with friends