kmp 快速模式串匹配
来源:互联网 发布:网络渠道销售授权书 编辑:程序博客网 时间:2024/04/30 23:58
题目要求:输入一个str串,输入一个将要匹配的match串,若匹配成功,返回match在str中的第一个位置,否则返回-1
举例 : str :abc123
match: 123
返回 3
import java.util.*;
public class Main{
public static void main(String[] args){
Scanner s=new Scanner(System.in);
String str=s.nextLine();
String match=s.nextLine();
System.out.println(getIndexOf(str,match));
}
public static int getIndexOf(String str,String match){
if(str==null|| match==null || match.length()<1 || match.length()> str.length())
return -1;
char []ss=str.toCharArray(); char []ms=match.toCharArray(); int []next=getNextArray(ms);
int si=0; int mi=0;
while(si<ss.length && mi<ms.length){
if(ss[si] == ms[mi]){
si++; mi++;
}else if(next[mi] == -1)
si++;
else
mi=next[mi];
}
return mi==ms.length ? si-mi :-1;
}
public static int[] getNextArray( char []ms){ //求next数组
if(ms.length == 1)
return new int[]{-1};
int []next=new int[ms.length];
next[0] = -1; next[1] = 0;
int pos = 2; int cn = 0;
while(pos<ms.length){
if(ms[pos-1] == ms[cn])
next[pos++] = ++cn;
else if(cn > 0)
cn=next[cn];
else
next[pos++]=0;
}
return next;
}
}
0 0
- kmp 快速模式串匹配
- KMP 快速模式匹配算法
- KMP-快速模式匹配算法
- 模式串匹配:KMP
- KMP 模式串匹配
- 快速模式匹配算法(KMP)
- 快速模式匹配算法(KMP)
- 快速模式匹配算法(KMP)
- 串模式匹配之------KMP
- KMP模式匹配 串1
- KMP模式匹配 串2
- 串的kmp模式匹配
- KMP 模式串匹配算法
- 串-KMP模式匹配算法
- 【模式串个数匹配】+ KMP
- KMP模式串匹配模板
- 快速匹配算法(KMP)
- KMP快速字符串匹配
- 多态
- 汇编语言 十六进制转换为二进制
- 苏嵌25 16.12.02
- 单例设计模式
- ProgressBar的样式及用法
- kmp 快速模式串匹配
- 微软认知服务 人脸识别 API 之 概述
- 练习题
- 写爬虫过程中的一个问题
- mac 设置代理做抓包调试
- 突破github的100M单个大文件上传限制
- Android内存优化总结
- NYoj811变态最大值
- codeforces 621E Wet Shack and blocks dp+矩阵幂优化!