获取next()数组
/**
* 获取next数组
* data 主字符串
* */
public static int[] getNext(String data){
int[] next=new int[data.length()] ;
next [0]=0;
int index=0;
for (int i = 1; i < next.length; i++) {
//获取当前下标的前一位覆盖表的值
index =next[i-1];
//比较 当前下标的字符与前一位字符的覆盖表的值对应的字符
if(data.charAt(index)==data.charAt(i)){
//若符合, 当前下标的覆盖值+1
next[i]=index+1;
}
else{
//若不符合,当前下标的覆盖值归零
next[i]=0;
}
}
return next;
}
匹配字符串
/**
* str 主字符串
* date 匹配字符串
* */
public static int find(String str,String data){
int[] next=getNext(data);
//主字符串下标
int i=0;
//匹配字符串下标
int j=0;
//统计匹配成功的次数
int count=0;
while(i++<str.length()){
if(count==data.length()){
//返回开始下标
return i+1-count;
}
if(str.charAt(i)==data.charAt(j)){
j++;
count++;
}else{
//匹配失败, 匹配字符串下标回朔
j=next[j];
count=j+1;
}
}
return -1;
}
测试案例
public static void main(String[] args) {
String res = Arrays.toString(getNext("abcdabd"));
System.out.println("next数组为:"+res);
int find = find("kajhdabcdabdasdaf","hda");
System.out.println("起始下标为:"+find);
}
输出结果
next数组为:[0, 0, 0, 0, 1, 2, 0]
起始下标为:3