Openjudge realize KMP
Total time limit: 1000ms memory limit: 65535kB
Describe
Give two strings A, b, and find out where B appears for the first time from a.
Input
The first line enters an integer t that represents the number of test data
For each set of test data, enter two string s t,s and T with a single space between each group of data.
The length of the s,t is no more than 20000
Output
For each set of test data, find the first occurrence of B in output A, if a does not contain B, output-1
Sample input
3
Aaaabaa Ab
AAABBB BB
XXXXXX YY
Sample output
3
3
-1
Tips
Using KMP fast matching algorithm can solve the problem.
#include <iostream> #include <string.h> using namespace std;
#define MAXSIZE 20001 int getNext (int next[],char s[]);
int getNext (int next[],char s[]) {int i;
int Length;
int t=0;
Length = strlen (s);
next[0]=0;
for (i = 1; i < Length; i++) {if (s[i] = = S[t]) {next[i] = t++;
else {Next[i] = t = 0;
} return 0;
int KMP (char T[],char s[]) {int i = 0,j = 0;
int lt,ls;
int next[maxsize];
GetNext (next,t);
Lt = strlen (t);
Ls = strlen (s);
while (I < Ls && J < lt) {if (s[i] = = T[j]) {j + +;
i++;
else if (S[i]!= t[j] && j = = 0) {i++;
else {j = next[j]; } return (j = Lt)?
I-LT:-1;
int main () {int n;
Char T[maxsize],s[maxsize]; Cin>> n;
while (n--) {cin>>s;
cin>>t;
COUT<<KMP (t,s) <<endl;
return 0;
}