Skip to content

Commit

Permalink
Added Java code for Z-Algorithm (jainaman224#785)
Browse files Browse the repository at this point in the history
Added Java code for Z-Algorithm
  • Loading branch information
Prashant Mahanta authored and jainaman224 committed Mar 25, 2019
1 parent e5d3b4a commit aac5710
Showing 1 changed file with 74 additions and 0 deletions.
74 changes: 74 additions & 0 deletions Z_Algorithm/Z_Algorithm.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@

public class Z_Algorithm {

static void getZarr(String str, int Z[]){

int n = str.length(), Left = 0, Right = 0, k;

for(int i = 1; i < n; i++)
{
if(i > Right)
{
Left = Right = i;

while(Right < n && str.charAt(Right - Left) == str.charAt(Right))
Right++;

Z[i] = Right - Left;
Right--;
}
else
{
k = i - Left;

if(Z[k] < Right - i + 1)
Z[i] = Z[k];
else
{
Left = i;

while(Right < n && str.charAt(Right - Left) == str.charAt(Right))
Right++;

Z[i] = Right - Left;
Right--;
}
}
}
}

static void search(String text, String pattern){

String concat = pattern + "$" + text;
int size = concat.length();
int Z[] = new int[size];

getZarr(concat, Z);

for(int i = 0; i < size; i++){
if(Z[i] == pattern.length()){
int index = i-pattern.length();
System.out.println("Pattern found at " + index);
}
}


}

public static void main(String args[]){

String text = "namanchamanbomanamansanam";
String pattern = "aman";
search(text, pattern);
}
}
/*
Sample Input:
namanchamanbomanamansanam (text)
aman (pattern)
Sample Output:
Pattern found at 2
Pattern found at 8
Pattern found at 17
*/

0 comments on commit aac5710

Please sign in to comment.