|
| 1 | +class GFG { |
| 2 | + |
| 3 | + // prints all occurrences of pattern in text using |
| 4 | + // Z algo |
| 5 | + public static void search(String text, String pattern) |
| 6 | + { |
| 7 | + |
| 8 | + // Create concatenated string "P$T" |
| 9 | + String concat = pattern + "$" + text; |
| 10 | + |
| 11 | + int l = concat.length(); |
| 12 | + |
| 13 | + int Z[] = new int[l]; |
| 14 | + |
| 15 | + // Construct Z array |
| 16 | + getZarr(concat, Z); |
| 17 | + |
| 18 | + // now looping through Z array for matching condition |
| 19 | + for(int i = 0; i < l; ++i){ |
| 20 | + |
| 21 | + // if Z[i] (matched region) is equal to pattern |
| 22 | + // length we got the pattern |
| 23 | + |
| 24 | + if(Z[i] == pattern.length()){ |
| 25 | + System.out.println("Pattern found at index " |
| 26 | + + (i - pattern.length() - 1)); |
| 27 | + } |
| 28 | + } |
| 29 | + } |
| 30 | + |
| 31 | + // Fills Z array for given string str[] |
| 32 | + private static void getZarr(String str, int[] Z) { |
| 33 | + |
| 34 | + int n = str.length(); |
| 35 | + |
| 36 | + // [L,R] make a window which matches with |
| 37 | + // prefix of s |
| 38 | + int L = 0, R = 0; |
| 39 | + |
| 40 | + for(int i = 1; i < n; ++i) { |
| 41 | + |
| 42 | + // if i>R nothing matches so we will calculate. |
| 43 | + // Z[i] using naive way. |
| 44 | + if(i > R){ |
| 45 | + |
| 46 | + L = R = i; |
| 47 | + |
| 48 | + // R-L = 0 in starting, so it will start |
| 49 | + // checking from 0'th index. For example, |
| 50 | + // for "ababab" and i = 1, the value of R |
| 51 | + // remains 0 and Z[i] becomes 0. For string |
| 52 | + // "aaaaaa" and i = 1, Z[i] and R become 5 |
| 53 | + |
| 54 | + while(R < n && str.charAt(R - L) == str.charAt(R)) |
| 55 | + R++; |
| 56 | + |
| 57 | + Z[i] = R - L; |
| 58 | + R--; |
| 59 | + |
| 60 | + } |
| 61 | + else{ |
| 62 | + |
| 63 | + // k = i-L so k corresponds to number which |
| 64 | + // matches in [L,R] interval. |
| 65 | + int k = i - L; |
| 66 | + |
| 67 | + // if Z[k] is less than remaining interval |
| 68 | + // then Z[i] will be equal to Z[k]. |
| 69 | + // For example, str = "ababab", i = 3, R = 5 |
| 70 | + // and L = 2 |
| 71 | + if(Z[k] < R - i + 1) |
| 72 | + Z[i] = Z[k]; |
| 73 | + |
| 74 | + // For example str = "aaaaaa" and i = 2, R is 5, |
| 75 | + // L is 0 |
| 76 | + else{ |
| 77 | + |
| 78 | + |
| 79 | + // else start from R and check manually |
| 80 | + L = i; |
| 81 | + while(R < n && str.charAt(R - L) == str.charAt(R)) |
| 82 | + R++; |
| 83 | + |
| 84 | + Z[i] = R - L; |
| 85 | + R--; |
| 86 | + } |
| 87 | + } |
| 88 | + } |
| 89 | + } |
| 90 | + |
| 91 | + // Driver program |
| 92 | + public static void main(String[] args) |
| 93 | + { |
| 94 | + String text = "GEEKS FOR GEEKS"; |
| 95 | + String pattern = "GEEK"; |
| 96 | + |
| 97 | + search(text, pattern); |
| 98 | + } |
| 99 | +} |
0 commit comments