less than 1 minute read

  • 분류: 문자열, KMP 알고리즘

코드

#include <iostream>
#include <string>
#include <vector>

using namespace std;

int pi_table[1000000]= {0, };

int main(){
    cin.tie(NULL);
    cout.tie(NULL);
    ios_base::sync_with_stdio(false);

    string T, P;
    getline(cin, T);
    getline(cin, P);

    // P 전처리
    int curr = 1;
    int match = 0;
    while(curr < P.size()){
        if(P[curr]==P[match]) pi_table[curr++] = ++match;
        else if(match==0) pi_table[curr++] = 0;
        else match = pi_table[match-1];
    }

    // T, P 비교
    vector<int> record;
    int num=0;

    curr = 0;
    match = 0;
    while(curr < T.size()) {
        if(T[curr]==P[match]){
            if(match==P.size()-1){
                num++;
                record.push_back(curr-match+1);

                if(match==0) curr++;
                else match = pi_table[match-1];
            }
            else{
                curr++;
                match++;
            }
        }
        else if(match==0) curr++;
        else match = pi_table[match-1];
    }

    cout << num << '\n';
    for(auto r : record) cout << r << ' ';
}

Tags:

Categories:

Updated: