数据结构中Java实现KMP与BF算法对比


public class KMPANDBF {
	public int indexBfCount(SeqString s,SeqString t,int begin){
		int slen,tlen,i=begin,j = 0;
		int count = 0;
		slen =s.length();
		tlen = t.length();
		while ((i<slen)&&(j<tlen)) {
			if (s.charAt(i)==t.charAt(j)) {
				i++;
				j++;
			}else{
				i = i - j +1;
				j = 0;
			}
			count++;
		}
		return count;
	}
	
	public int indexKMPCount(SeqString s,SeqString t, int begin) {
		int[] next = getNext(t);
		int i =begin ;
		int j =0;
		int count = 0;
		while (i<s.length()&&j<t.length()) {
			if (j == -1||s.charAt(i) == t.charAt(j)) {
				i++;
				j++;
			}else if(j == 0){
				i++;
			}else {
				j = next[j];
			}
			count++;
		}
		return count;
	}
	
	public int[] getNext(SeqString T) {
		int[] next = new int[T.length()];
		int j =1;
		int k = 0;
		next[0] = -1;
		next[1] = 0;
		while (j<T.length()-1) {
			if (T.charAt(j)==T.charAt(k)) {
				next[j+1] = k +1;
				j++;
				k++;
			}else if (k == 0) {
				next[j +1]=0;
				j++;
			}else {
				k = next[k];
			}
		}
		return (next);
	}
	public static void main(String[] args) {
		SeqString s1 =new SeqString("abcdbacc");
		SeqString t1 =new SeqString("abcd");
		KMPANDBF c =new KMPANDBF();
		System.out.println("测试1:主串 S = "+ s1.toString()+", 模式串 T = "+ t1.toString());
		System.out.println("BF算法比较次数: "+c.indexBfCount(s1, t1, 0) );
		System.out.println("KMP算法比较次数:" +c.indexKMPCount(s1, t1, 0));
		
		SeqString s2 = new SeqString("aaaaaaaaa");
		SeqString t2 = new SeqString("aaaab");
		
		System.out.println("测试1:主串 S = "+ s2.toString()+", 模式串 T = "+ t2.toString());
		System.out.println("BF算法比较次数: "+c.indexBfCount(s2, t2, 0) );
		System.out.println("KMP算法比较次数:" +c.indexKMPCount(s2, t2, 0));
	}
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值