KMP String Matching Algorithm

  This is a program based on Knuth-Morris-Pratt String Matching Algorithm (a.k.a KMP algorithm), which can be tapped to solve the problem POJ 3461.

 1 import java.io.*;
 2 import java.util.*;
 3 
 4 class Input {
 5     private Scanner in;
 6     private StringTokenizer tok;
 7     
 8     public Input() {
 9         in = new Scanner(new BufferedInputStream(System.in));
10     }
11     public String nextString() {
12         while  (tok==null||!tok.hasMoreTokens()) {
13             tok = new StringTokenizer(in.nextLine());
14         } 
15         return tok.nextToken();
16     }
17     public int nextInt() {
18         while  (tok==null||!tok.hasMoreTokens()) {
19             tok = new StringTokenizer(in.nextLine());
20         } 
21         return Integer.parseInt(tok.nextToken());
22     }
23     public double nextDouble() {
24         while  (tok==null||!tok.hasMoreTokens()) {
25             tok = new StringTokenizer(in.nextLine());
26         } 
27         return Double.parseDouble(tok.nextToken());
28     }
29     public void close() {
30         in.close();
31     }
32 }
33 
34 public class Main {
35     
36     public static int[] preproc(String pattern)  {
37         int[] dp = new int[pattern.length()];
38         Arrays.fill(dp,-1);
39         for (int i=1;i<pattern.length();i++) {
40             for (int j=i-1;j>=0;j=dp[j]) {
41                 if (pattern.charAt(dp[j]+1)==pattern.charAt(i)) {
42                     dp[i] = dp[j]+1;
43                     break;
44                 }
45             }
46         }
47         return dp;
48     }
49     public static int match(String pattern,String test) {
50         int[] next = preproc(pattern);
51         int cnt = 0;
52         for (int i=0,j=0;i<test.length();) {
53             if (test.charAt(i)==pattern.charAt(j)) {
54                 ++i;
55                 if (++j==pattern.length()) {
56                     cnt++;
57                     j = next[j-1]+1;
58                 }
59             } else if (j>0) {
60                 j = next[j-1]+1;
61             } else {
62                 i++;
63             }
64         }
65         return cnt;
66     }
67     public static void main(String[] args) {
68         Input in = new Input();
69         int time = in.nextInt();
70         for (int t=0;t<time;t++) {
71             System.out.println(match(in.nextString(),in.nextString()));
72         }
73         in.close();
74     }
75 }
原文地址:https://www.cnblogs.com/DevinZ/p/4462154.html