左神_基础提升班_03_kmp和manacher算法
作者:互联网
1.kmp算法
public static int getIndexOf(String s, String m) {
if(s==null||m==null||m.length()<1||m.length()>s.length()){
return -1;
}
char[] cs = s.toCharArray();
char[] cm = m.toCharArray();
int i=0;
int j=0;
int[] next=getNextArray(cm);
while(i<s.length()&&j<m.length()){
if(cs[i]==cm[j]){
i++;
j++;
}else if(next[j]>-1){
j=next[j];
}else{
i++;
}
}
return j==m.length()?i-j:-1;
}
public static int[] getNextArray(char[] ms) {
if(ms.length==1){
return new int[]{-1};
}
int [] next=new int[ms.length];
next[0]=-1;
next[1]=0;
int i=2;
int cn=0;
while(i<next.length){
if(ms[i-1]==ms[cn]){
cn++;
next[i]=cn;
i++;
}else if(cn>0){
cn=next[cn];
}else{
next[i++]=0;
}
}
return next;
}
public static void main(String[] args) {
String str = "abcabcababaccc";
String match = "ababa";
System.out.println(getIndexOf(str, match));
}
2.manacher算法
public static char[] manacherString(String str) {
char[] charArr = str.toCharArray();
char[] res = new char[str.length() * 2 + 1];
int index = 0;
for (int i = 0; i != res.length; i++) {
res[i] = (i & 1) == 0 ? '#' : charArr[index++];
}
return res;
}
public static int maxLcpsLength(String str) {
if (str == null || str.length() == 0) {
return 0;
}
char[] charArr = manacherString(str);//1221 ->#1#2#2#1#
int[] pArr = new int[charArr.length];//回文半径数组
int C = -1;//中心位置
int R = -1;//回文右边界的再往右一个位置,最右的有效区是R-1位置
int max = Integer.MIN_VALUE;//扩出来的最大值
for (int i = 0; i != charArr.length; i++) {//每一个位置求回文半径
pArr[i] = R > i ? Math.min(pArr[2 * C - i], R - i) : 1; //i至少的回文区域,先给pArr[i],4种情况都包括了
while (i + pArr[i] < charArr.length && i - pArr[i] > -1) {//都要扩,为了写得代码少,不用扩的执行一步就会失败
if (charArr[i + pArr[i]] == charArr[i - pArr[i]])
pArr[i]++;
else {
break;
}
}
if (i + pArr[i] > R) {//若大于R就会更新
R = i + pArr[i];
C = i;
}
max = Math.max(max, pArr[i]);
}
return max - 1;//#1#2#1# 2的回文半径为4,原串121的回文字符串长度为4-1=3
}
public static void main(String[] args) {
String str1 = "abc1234321ab";
System.out.println(maxLcpsLength(str1));
}
标签:03,String,int,manacher,左神,next,++,length,pArr 来源: https://blog.csdn.net/zhiyongbo/article/details/115300495