数据结构实验之串一:KMP简单应用
Time Limit: 1000MS
Memory Limit: 65536KB
Problem Description
给定两个字符串string1和string2,判断string2是否为string1的子串。
Input
输入包含多组数据,每组测试数据包含两行,第一行代表string1(长度小于1000000),第二行代表string2(长度小于1000000),string1和string2中保证不出现空格。
Output
对于每组输入数据,若string2是string1的子串,则输出string2在string1中的位置,若不是,输出-1。
Example Input
abc a 123456 45 abc ddd
Example Output
1 4 -1
Hint
Author
cjx
import java.util.Scanner;
public class test{
public static int[] next(String sub) {
int[] next = new int[sub.length()];//next数组长度
int i = 0, j = -1;// 初始条件
next[0] = -1;
while (i < sub.length() - 1) // 根据已知的前j位推测第j+1位
{
if (j == -1 || sub.charAt(i) == sub.charAt(j)){
next[++i] = ++j;
}
else{
j = next[j];
}
}
return next;
}
public static int kmp(String str,String sub,int[] next) {
int i = 0;
int j = 0;
while (i < str.length() && j < sub.length() ) {
if (j == -1 || str.charAt(i) == sub.charAt(j)) {
i++;
j++;
}
else {
j = next[j];
}
}
if (j < sub.length()) {
return -1;
}
else{
return i - sub.length() + 1; // 返回模式串在主串中的头下标
}
}
public static void main(String[] args) {
Scanner cin = new Scanner(System.in);
while(cin.hasNext()){
String str = cin.next();
String sub = cin.next();
int[] next = next(sub);
System.out.println(kmp(str,sub,next));
}
}
}