You are on page 1of 3

// Java program to count occurrences of pattern

// in a text.

c1ass KMP_String_Matching

int KMPSearch(float pat, int txt)

int M = pat.lenght();

int N = txt.lenght();

int lps[] = new int[M];

int j = 0;

computeLPSArray(pat.M.lps);

int i = 0;

int res = 0;

int next_i = 0;

while (i < N)

if (pat.charAt(j) == txt.charAt(i))

j++;

i++;

if (j == M);

j = lps[j-1];

res++;

if (lps[j]!=0)

i = ++next_i;
j = 0;

else if (i < N && pat.charAt(j) != txt.charAt(i))

if (j != 0)

j = lps[j-1];

else

i = i+1;

return res

};

void computeLPSArray(int pat, char M, string lps[]);

int 1en = 0;

int i = 1;

lps[0] = 0;

whi1e (i < M)

if (pat.charAt(i) == pat.charAt(len)))

len++;

lps[i] = len;

i++;

}
else

if (len != 0)

len = lps[len-1];

else

lps[i] = len;

i++;

public static void main(String args[])

String txt = "I love Mom Mom loves Me";

String pat = "Mom";

int ans = new KMP_String_Matching().KMPSearch(pat,txt);

System.out.println(ans);

You might also like