KMP
题目描述
KMP代码
import java.util.Scanner;
import com.sun.org.apache.regexp.internal.recompile;
public class Main{
static int next[] = new int[1005];
static char ch1[] = new char[100005];
static char ch2[] = new char[1005];
public static void main(String [] args) {
next[1] = 0;
Scanner scanner2 = new Scanner(System.in);
String s = scanner2.nextLine();
s = " "+s;
int len = s.length();
ch1 = s.toCharArray();
int n = scanner2.nextInt();
for(int x= 1;x<=n;x++) {
String ss = scanner2.next();
ss = " "+ss;
ch2 = ss.toCharArray();
int leng = ss.length();
getNext(ch2, leng);
int i = 1;
int j = 1;
int sum = 0;
while(i<len) {
if(ch1[i]==ch2[j]) {
i++;
j++;
}
else {
if(j==1) {
i++;
}
else {
j = next[j];
}
}
if(j==leng) {
sum++;
j= next[j];
}
}
System.out.println(sum);
}
}
public static void getNext(char ch[],int len) {
int i = 1;
int j = 0;
while(i<len) {
if(j==0||ch[i]==ch[j])
next[++i] = ++j;
else
j = next[j];
}
}
}
暴力
import java.util.*;
public class Main {
public static void main(String arg[]) {
Scanner sc = new Scanner(System.in);
String string = sc.nextLine();
int n = sc.nextInt();
int len = string.length();
for(int i =0;i<n;i++) {
String str = sc.next();
int leng = str.length();
int sum = 0;
for(int j = 0;j<len;j++) {
if(string.indexOf(str,j)!=-1) {
sum++;
j = string.indexOf(str,j);
}
}
System.out.println(sum);
}
}
}