KMP Matching: String Matching
2015-05-19 07:39
295 查看
KMP matching:
Pseudo code:
Java code:
/** * Created with IntelliJ IDEA. * User: 1O1O * Date: 2015-03-31 * Time: 12:01 PM * :)~ * KMP-MATCH:STRING-MATCH */ public class Main { public static int[] COMPUTE_PREFIX_FUNCTION(String P_sub){ int m = P_sub.length(); char[] P_sub_char = P_sub.toCharArray(); int[] pie = new int[m]; pie[0] = 0; int k = 0; for(int q=2; q<=m; q++){ while (k>0 && P_sub_char[k]!=P_sub_char[q-1]){ k = pie[k]; } if(P_sub_char[k] == P_sub_char[q-1]){ k = k+1; } pie[q-1] = k; } System.out.println("Prefix results: "); for(int r=0; r<m; r++){ System.out.println("Pie["+r+"]="+pie[r]); } return pie; } public static void KMP_MATCHER(String T_full, String P_sub){ int n = T_full.length(); int m = P_sub.length(); char[] T_full_char = T_full.toCharArray(); char[] P_sub_char = P_sub.toCharArray(); int[] pie = COMPUTE_PREFIX_FUNCTION(P_sub); int q = 0; for(int i=1; i<=n; i++){ while (q>0 && P_sub_char[q]!=T_full_char[i-1]){ q = pie[q-1]; } if(P_sub_char[q]==T_full_char[i-1]){ q = q+1; } if(q == m){ System.out.println("Pattern occurs with shift: "+(i-m+1)); q = pie[q-1]; } } } public static void main(String[] args) { String T_full = "bacbababaabcbabababacababbababacabbc"; String P_sub = "ababaca"; KMP_MATCHER(T_full, P_sub); } }
Output:
Prefix results: Pie[0]=0 Pie[1]=0 Pie[2]=1 Pie[3]=2 Pie[4]=3 Pie[5]=0 Pie[6]=1 Pattern occurs with shift: 16 Pattern occurs with shift: 27
Reference:
From: 《INTRODUCTION TO ALGORITHMS》THIRD EDITION.
相关文章推荐
- POJ 1580 String Matching 很纠结,代码写了很多,还是过了,再对比一下人家的代码,惭愧
- hdoj 1306 String Matching
- 九度oj-1094-String Matching
- 字符串匹配(String Matching)
- String matching整理
- String Matching(poj1580)
- 字符串匹配(string matching)算法之一 (Naive and Rabin_Karp)
- 【字符串】poj1582 String Matching
- Kattis - String Matching(kmp)
- 字符串匹配(string matching)算法之二:利用有限自动机
- hdu 1036 String Matching
- 题目1094:String Matching
- ZOJ 1170 String Matching
- poj 1580 String Matching 【字符串处理】
- 时空权衡——字符串匹配(Time/Space Tradeoff - Horspool's String Matching)
- 字符串匹配(string matching)算法之一 (Naive and Rabin_Karp)
- hdu-1306- String Matching
- 杭电1306 String Matching
- HDU1306 String Matching 【暴力】
- 字符串匹配(string matching)算法之二:利用有限自动机