Online JudgeProblem SetAuthorsOnline ContestsUser
Web Board
Home Page
F.A.Qs
Statistical Charts
Problems
Submit Problem
Online Status
Prob.ID:
Register
Update your info
Authors ranklist
Current Contest
Past Contests
Scheduled Contests
Award Contest
User ID:
Password:
  Register

来一发KMP模板

Posted by KatrineYang at 2017-01-26 13:44:42 on Problem 1572
#include <iostream>
#include <string>
#include <vector>
#include <stdio.h>
#include <cstdlib>
using namespace std;

void buildBorderArray(int *border, string& s) {
     int size = s.size();
     //cout << s.size() << endl;
     //border = new int[s.size() + 1];
     border[0] = -1;
     for(int i = 0; i < size-1; i++){
             int bor = border[i];
             while(bor >= 0 && s[i+1] != s[bor + 1]){
                       bor = border[bor];
             }
             if(s[i+1] == s[bor + 1]) border[i+1] = bor + 1;
             else border[i+1] = -1;
             //cout << border[i+1] << endl;
     }
}

int searchKmp(string& str, string& pat, int *border){
            int patsize = pat.size();
            int strsize = str.size();
            buildBorderArray(border, pat);
            int i = 0, j = 0;
            while(i <= strsize - patsize){
                    while(j < patsize && str[i] == pat[j]){
                            i++; j++;
                            //cout << i << " " << j << endl;
                    }
                    if(j == patsize) {
                    	return i - patsize;
                    }
                    if(j == 0) i++;
                    else j = border[j-1] + 1;
            }
            return -1;
}

int main() {
	int gs;
	while(1){
		string s;
		getline(cin,s);
		gs = atoi(s.c_str());
		if(!gs) break;
		string occ[15], rep[15];
		for(int i = 0; i < gs; i++){
			getline(cin, occ[i]);
			getline(cin, rep[i]);
		}
		getline(cin, s);
		for(int i = 0; i < gs; i++){
			int patsize = occ[i].length();
			int *border = new int[patsize + 1];
			buildBorderArray(border, occ[i]);
			while(1){
				int repPlc = searchKmp(s, occ[i], border);
				if(repPlc == -1) break;
				s = s.substr(0,repPlc) + rep[i] + s.substr(repPlc+patsize);
			}
			delete [] border;
		}
		cout << s << endl;
	}
	return 0;
}

Followed by:

Post your reply here:
User ID:
Password:
Title:

Content:

Home Page   Go Back  To top


All Rights Reserved 2003-2013 Ying Fuchen,Xu Pengcheng,Xie Di
Any problem, Please Contact Administrator