KMP在Java中的实现indexOf()
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
String s = br.readLine();
int c = Integer.parseInt(br.readLine());
int m = Integer.parseInt(br.readLine());
if(c==0) s = s.toLowerCase();
String ps = "",psc = "";
while(m-->0) {
ps = br.readLine();
if(c==0) {
psc = ps.toLowerCase();
}else {
psc = ps;
}
if(process(psc,s)) {
bw.write(ps+"\n");
}
}
bw.flush();
}
private static boolean process(String psc, String s) {
return psc.indexOf(s)!=-1;
}
}
再补上一个KMP
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
String s = br.readLine();
int c = Integer.parseInt(br.readLine());
int m = Integer.parseInt(br.readLine());
if(c==0) s = s.toLowerCase();
String ps = "",psc = "";
while(m-->0) {
ps = br.readLine();
if(c==0) {
psc = ps.toLowerCase();
}else {
psc = ps;
}
// if(psc.indexOf(s)!=-1) bw.write(ps+"\n");
if(KMP(psc,s)) bw.write(ps+"\n");
}
bw.flush();
}
private static boolean KMP(String psc, String s) {
char[] a1 = (" "+s).toCharArray();
char[] a2 = (" "+psc).toCharArray();
int len = s.length();
int n = psc.length();
int ne[] = new int[len+1];
ne[1] = 0;
for(int i = 2, j = 0;i <= len ; i ++) {
while(j!=0&&a1[i]!=a1[j+1]) j = ne[j];
if(a1[i]==a1[j+1]) j++;
ne[i] = j;
}
for(int i = 1,j = 0; i <= n;i++) {
while(j!=0&&a2[i]!=a1[j+1]) j = ne[j];
if(a2[i]==a1[j+1]) j++;
if(j==len) {
return true;
}
}
return false;
}
}