题目链接 http://acm.hdu.edu.cn/showproblem.php?pid=2087
程序一 KMP 算法
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scn = new Scanner(System.in);
while (true) {
String str1 = scn.next();
if ("#".equals(str1)) {
break;
}
String str2 = scn.next();
Kmp kmp = new Kmp(str1.toCharArray(), str2.toCharArray());
System.out.println(kmp.match());
}
scn.close();
}
}
class Kmp {
private int modelLength;
private int patternLength;
private char[] model;
private char[] pattern;
private int[] next;
private void calculateNext() {
int i = 0, j = -1;
next[0] = -1;
while (i < patternLength - 1) {
if (-1 == j || pattern[i] == pattern[j]) {
++i;
++j;
if (pattern[i] != pattern[j]) {
next[i] = j;
} else {
next[i] = next[j];
}
} else {
j = next[j];
}
}
}
public Kmp(char[] model, char[] pattern) {
modelLength = model.length;
patternLength = pattern.length;
this.model = model;
this.pattern = pattern;
next = new int[patternLength];
}
public int match() {
calculateNext();
int i = 0, j = 0, count = 0;
while (i < modelLength && j < patternLength) {
if (-1 == j || model[i] == pattern[j]) {
++i;
++j;
} else {
j = next[j];
}
if (j >= patternLength) {
++count;
j = 0;
}
}
return count;
}
}
程序二 String类的indexOf方法
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scn = new Scanner(System.in);
while (true) {
String str1 = scn.next();
if ("#".equals(str1)) {
break;
}
String str2 = scn.next();
int position = str1.indexOf(str2, 0);
int count = 0;
while (0 <= position) {
++count;
position = str1.indexOf(str2, position + str2.length());
}
System.out.println(count);
}
scn.close();
}
}