【数据结构与算法】[hihoCode] #1015 : KMP算法(解决Time Limit Exceeded)
2017-05-29 17:42
405 查看
博主在做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); } } }
相关文章推荐
- 【数据结构与算法】字符串匹配KMP算法
- 【数据结构与算法】字符串匹配之BF&KMP算法
- JavaScript中数据结构与算法(五):经典KMP算法
- 数据结构20:KMP算法(快速模式匹配算法)详解
- 数据结构与算法之哈希冲突解决-链地址法与开放定址法对比
- C++ 数据结构之kmp算法中的求Next()函数的算法
- 数据结构之字符串匹配算法(BF算法和KMP算法)
- 【数据结构与算法】模式匹配——从BF算法到KMP算法(附完整源码)
- 数据结构(11)--串的模式匹配算法之BF、KMP算法
- Java数据结构之字符串模式匹配算法---KMP算法
- 数据结构之串解决BF和KMP算法
- [数据结构与算法]BF算法与KMP算法实现
- spark-OutOfMemory:GC overhead limit exceeded 解决,timelimitexceeded
- JavaScript中数据结构与算法(五):经典KMP算法
- 数据结构与算法_KMP算法
- 【数据结构与算法】模式匹配——从BF算法到KMP算法(附完整源码)
- 数据结构与算法:python语言描述学习笔记Part4_kmp算法及改进
- 数据结构及算法-何谓数据结构
- Crazybit开发手记(一):设计之数据结构和算法的分离
- 数据结构与算法(C#实现)系列---AVLTree(二)(外摘)