You are on page 1of 2

12/10/2018, 6)09 PM

1 import java.io.BufferedReader;
2 import java.io.IOException;
3 import java.io.InputStreamReader;
4 import java.util.*;
5
6 public class KnuthMorrisPratt {
7 class FastScanner {
8 StringTokenizer tok = new StringTokenizer("");
9 BufferedReader in;
10
11 FastScanner() {
12 in = new BufferedReader(new InputStreamReader(System.in));
13 }
14
15 String next() throws IOException {
16 while (!tok.hasMoreElements())
17 tok = new StringTokenizer(in.readLine());
18 return tok.nextToken();
19 }
20
21 int nextInt() throws IOException {
22 return Integer.parseInt(next());
23 }
24 }
25
26 // Find all the occurrences of the pattern in the text and return
27 // a list of all positions in the text (starting from 0) where
28 // the pattern starts in the text.
29 public int[] calcPrefix(String text) {
30 int[] array=new int[text.length()];
31 array[0]=0;
32 int dist=0;
33 for (int i = 1; i < array.length; i++) {
34 while(dist>0&&text.charAt(dist)!=text.charAt(i))
35 dist=array[dist-1];
36 if(text.charAt(dist)==text.charAt(i))
37 dist++;
38 else
39 dist=0;
40 array[i]=dist;
41 }
42 return array;
43 }
44 public List<Integer> findPattern(String pattern, String text) {
45 ArrayList<Integer> result = new ArrayList<Integer>();
46 // Implement this function yourself
47 String txt=pattern+"$"+text;
48 int[] arr=calcPrefix(txt);
49 // Utility.PrintArray(arr);
50 for (int i = pattern.length()+1; i < txt.length(); i++) {
51 if(arr[i]==pattern.length())
52 result.add(i-2*pattern.length());
53 }
54 return result;
55 }
56
57 static public void main(String[] args) throws IOException {
58 new KnuthMorrisPratt().run();
59 }
60
61 public void print(List<Integer> x) {
62 for (int a : x) {
63 System.out.print(a + " ");
64 }
65 System.out.println();
66 }
67
68 public void run() throws IOException {
69 FastScanner scanner = new FastScanner();

https://uc333eda02f12f0b09160be95f73.previews.dropboxusercont…GbGUjEOl7f6iYK2iGeFCZT2sPI7i8yymotjD-xV2_Xh44SF3twnKxA/p.html Page 1 of 2
12/10/2018, 6)09 PM

70 String pattern = scanner.next();


71 String text = scanner.next();
72 List<Integer> positions = findPattern(pattern, text);
73 print(positions);
74 }
75 }

https://uc333eda02f12f0b09160be95f73.previews.dropboxusercont…GbGUjEOl7f6iYK2iGeFCZT2sPI7i8yymotjD-xV2_Xh44SF3twnKxA/p.html Page 2 of 2