【数据结构与算法】[hihoCode] #1015 : KMP算法(解决Time Limit Exceeded)

博主在做hihoCode的#1015 : KMP算法时,用了传统的KMP算法,但是一直报错“Time Limit Exceeded ”,网上查询很久,不断修改代码,最终Accepted。所以记录其中最关键部分,以备大家交流~


题设求,匹配串中有多少个模式串?

传统KMP是返回模式串在匹配串中的位置,下面进入正题,怎样利用KMP算法的思想(匹配串永不回溯)?正解是求next数组时,增加一位。如图所示:
这里写图片描述

为什么要增加一位next?

由于本题求的是匹配串中有多少个模式串,所以当模式串遍历一遍后,需要继续遍历匹配串直至匹配串也遍历一遍,才能统计出有多少个模式串。找到一个模式串,再找第二个时,令j=next[j],就能使匹配串不回溯,从而大大节省运行时间,形象图解如下:
这里写图片描述

代码分享

import java.util.*;

public class Main{
    public static int[] next(String pattern){
        int[] next=new int[pattern.length()+1];
        int k=-1;
        int j=0;
        next[0]=k;
        while(j<pattern.length()){
            if (k==-1||pattern.charAt(k)==pattern.charAt(j)){
                next[++j]=++k;
            }else{
                k=next[k];
            }
        }
        return next;
    }
    public static int search(String match,String pattern,int[] next){
        int i=0;
        int j=0;
        int count=0;
        while(i<match.length()){
            if(j==-1||pattern.charAt(j)==match.charAt(i)){
                j++;
                i++;
            }else{
                j=next[j];
            }
            if(j==pattern.length()){

                count++;

                j=next[j];
            }
        }

        return count;
    }
    public static void main(String[] args){
        Scanner sc=new Scanner(System.in);
        int num=Integer.valueOf(sc.nextLine());
        for(int i=0;i<num;i++){
            String pattern=sc.nextLine();
            String match=sc.nextLine();
            int[] next=next(pattern);
            //System.out.println(Arrays.toString(next));
            int count=search(match,pattern,next);

            System.out.println(count);
        }

    }
}

猜你喜欢

转载自blog.csdn.net/qq_29340857/article/details/72803126