博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
java实现KMP字符串匹配算法
阅读量:7078 次
发布时间:2019-06-28

本文共 1700 字,大约阅读时间需要 5 分钟。

hot3.png

研究了一下KMP的字符串匹配算法,其核心思想与朴素匹配算法的区别主要就在于:主串的index指针不回溯。

而子串的指针j只回到next[j]的位置。

注意:KMP算法只有在主串与子串存在比较多的部分匹配,才能显出其性能优势。

以下是算法实现。

KMP:

package aray.Test;public class KMP {	static int count=0;	static int next[] = new int[100];	public static void getNext(String sub) {		int i = 1, j = 0;		next[1] = 0;		char[] T = sub.toCharArray();		while (i < T.length) {			if (j == 0 || T[i] == T[j]) {				i++;				j++;				next[i] = j;			} else {				j = next[j];			}		}	}	public static int index(String pri, String sub) {		int i = 0, j = 0;		char[] P = pri.toCharArray();		char[] S = sub.toCharArray();        getNext(sub);		while (i < P.length && j < S.length) {						if (j == 0 || P[i] == S[j]) {				i++;				j++;			} else {				j = next[j];			}						count++;		}		if (j >= S.length) {			return i - j;		} else			return 0;	}	public static void main(String[] args) {		String str = "adcsadcsadcsadcsadcsadafa";		String sub = "csada";        System.out.println(index(str,sub));        System.out.println("the total count of compare is:  "+count);         	}}

朴素匹配:

package aray.Test;public class PuShu {	static int count=0;		public static int index(String pri, String sub) {		int i =0, j = 0;		char[] P = pri.toCharArray();		char[] S = sub.toCharArray();		while (i < P.length && j < S.length) {						if (P[i] == S[j]) {				i++;				j++;			} else {				i=i-j+1;				j=0;			}						count++;		}		if (j >= S.length) {			return i - j;		} else			return 0;	}			public static void main(String[] args) {		String str = "adcsadcsadcsadcsadcsadafa";		String sub = "csada";        System.out.println(index(str,sub));        System.out.println("the total count of compare is:  "+count);         	}}

转载于:https://my.oschina.net/aibati2008/blog/341253

你可能感兴趣的文章
c语言:将三个数按从大到小输出。
查看>>
WMI-Win32_PhysicalMemory 内存条参数
查看>>
常用的ICON图标网站
查看>>
深入分析Sleep(0)与Sleep(1)的区别
查看>>
nsq使用的TOML配置文件规范文档中文版
查看>>
Linux6.0命令界面与图形界面的切换
查看>>
Linux系统启动5个阶段
查看>>
KeyMob移动广告聚合平台 开发者赚钱平台
查看>>
GNU/Linux下LVM配置管理以及快照卷、物理卷、卷组、逻辑卷的创建和删除
查看>>
kvm虚拟化学习笔记(十三)之kvm虚拟机磁盘文件读取小结
查看>>
Centos6.5 安装淘宝 tengine
查看>>
centos7 内存硬件信息检测
查看>>
SQL Server vs Oracle 简单语法比较
查看>>
javascript 生成一个指定大小的居中div层
查看>>
Jedis cluster集群初始化源码剖析
查看>>
Linux iostat命令详解
查看>>
Java中的并发工具
查看>>
混合的方式开启服务
查看>>
C库数学函数
查看>>
vlan划分及vlan间通信
查看>>