题目:
给定一个字符串s和一个模式串p, 返回s中所有与p匹配的字符串开始下标
分析:
KMP算法, 解释看这里
package hello;
import java.util.ArrayList;
import java.util.List;
public class KMP {
public static List<Integer> kmp(String s, String p){
List<Integer> res = new ArrayList<Integer>();
if(s == null || p == null || s.length()<p.length())
return res;
char[] sArr = s.toCharArray();
char[] pArr = p.toCharArray();
int[] next = getNext(p);
int i=0, j=0;
while(i<sArr.length){
while(j<pArr.length){
//加判断防止i溢出
if(i>=sArr.length)
break;
//j为-1或匹配,则两数组往后遍历
if(j==-1 || sArr[i]==pArr[j]){
i++;
j++;
}else{
//匹配失败,在next数组中找到应该移动到的位置
j = next[j];
}
}
if(j==pArr.length){
res.add(i-j);
j=0;
}
}
return res;
}
//根据模式串计算next数组, next数组记录如果当前

该博客介绍了如何使用KMP算法解决在给定字符串s中找到与模式串p匹配的所有子串的起始下标的问题。通过KMP算法,可以有效地避免不必要的字符比较,提高搜索效率。
最低0.47元/天 解锁文章
1324

被折叠的 条评论
为什么被折叠?



