POJ 3461 Oulipo (KMP)

原题链接

题意
第一行是n,接下来是n个case。
每个case包含两行:模式串和主串各一行。
请你输出一行:模式串在主串中的出现次数

代码实现

import java.util.*;

public class Main {
    public static void main(String args[]){
        Scanner in=new Scanner(System.in);
        int T=in.nextInt();
        for(int t=0;t<T;t++){
            char[] sub=in.next().toCharArray();
            char[] str=in.next().toCharArray();
            int lensub=sub.length,lenstr=str.length;
            int[] Next=new int[lensub+10];
            //KMP getNext
            int i=0,j=-1;Next[0]=-1;
            while(i!=lensub){
                if(j==-1||sub[i]==sub[j]){
                    ++i;
                    ++j;
                    Next[i]=j;
                }
                else
                    j=Next[j];
            }
            //KMP getAns
            int ans=0;i=0;j=0;
            while(i!=lenstr&&j!=lensub){
                if(j==-1||str[i]==sub[j]){
                    ++i;
                    ++j;
                }
                else
                    j=Next[j];
                if(j==lensub){
                    ans++;
                    j=Next[j];
                }
            }
            System.out.println(ans);
        }
    }
}

By YOUSIKI

你可能感兴趣的:(POJ 3461 Oulipo (KMP))