KMP算法

本文详细介绍了Knuth-Morris-Pratt(KMP)算法和暴力搜索在处理字符串匹配问题中的实现,通过KMP算法的高效性与暴力搜索的对比,突出了KMP算法在大量数据场景下的优势。
摘要由CSDN通过智能技术生成

KMP

题目描述

在这里插入图片描述

KMP代码

import java.util.Scanner;
import com.sun.org.apache.regexp.internal.recompile;
public class Main{
	static int next[] = new int[1005];
	static char ch1[] = new char[100005];
	static char ch2[] = new char[1005];
	public static void main(String [] args)  {
		next[1] = 0;
		Scanner scanner2 = new Scanner(System.in);
		String s = scanner2.nextLine();
		s = " "+s;
		int len = s.length();
		ch1 = s.toCharArray();
		int n = scanner2.nextInt();
		for(int x= 1;x<=n;x++) {
			String ss = scanner2.next();
			ss = " "+ss;
			ch2 = ss.toCharArray();
			int leng = ss.length();
			getNext(ch2, leng);
			int i = 1;
			int j = 1;
			int sum = 0;
			while(i<len) {
				if(ch1[i]==ch2[j]) {
					i++;
					j++;
				}
				else {
					if(j==1) {
						i++;
					}
					else {
						j = next[j];
					}
				}
				if(j==leng) {
					sum++;
					j= next[j];

				}
			}
			System.out.println(sum);
			
		}
	}
	public static void getNext(char ch[],int len) {
		int i = 1;
		int j = 0;
		while(i<len) {
			if(j==0||ch[i]==ch[j])
				next[++i] = ++j;
			else
				j = next[j];
		}
	}
}

暴力

import java.util.*;
public class Main {
	public static void main(String arg[]) {
		Scanner sc = new Scanner(System.in);
		String string = sc.nextLine();
		int n = sc.nextInt();
		int len = string.length();
		for(int i =0;i<n;i++) {//100
			String  str = sc.next();
			int leng = str.length();
			int sum = 0;
			for(int j = 0;j<len;j++) {//主串长度100000
				if(string.indexOf(str,j)!=-1) {//1000*100000
					sum++;
					j = string.indexOf(str,j);//
				}			
			}
			System.out.println(sum);
		}
	}
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值