Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class KMPAlgo {
- public static void main(String[] args) {
- String txt = "ABABDABACDABABCABAB";
- String pattern = "ABABCABAB";
- int[] lps = computeLPS(pattern);
- countOccurance(txt, pattern, lps);
- }
- public static void countOccurance(String txt, String pat, int[] lps) {
- if (pat == null || pat.isEmpty() || txt == null || txt.isEmpty()) {
- return;
- }
- int M = pat.length();
- int N = txt.length();
- int indexForPattern = 0;
- int positionForTExt = 0;
- while (positionForTExt < N) {
- if (pat.charAt(indexForPattern) == txt.charAt(positionForTExt)) {
- indexForPattern++;
- positionForTExt++;
- }
- if (indexForPattern == M) {
- System.out.println("Found pattern " + "at index " + (positionForTExt - indexForPattern));
- indexForPattern = lps[indexForPattern - 1];
- }
- // mismatch after j matches
- else if (positionForTExt < N && pat.charAt(indexForPattern) != txt.charAt(positionForTExt)) {
- if (indexForPattern != 0) {
- indexForPattern = lps[indexForPattern - 1];
- } else {
- positionForTExt = positionForTExt + 1;
- }
- }
- }
- }
- public static int[] computeLPS(String pattern) {
- if (pattern == null || pattern.isEmpty()) {
- return null;
- }
- int[] lps = new int[pattern.length()];
- int index = 1;
- lps[0] = 0;
- int curLen = 0;
- while (index < pattern.length()) {
- if (pattern.charAt(index) == pattern.charAt(curLen)) {
- curLen++;
- lps[index] = curLen;
- index++;
- } else {
- if (curLen != 0) {
- curLen = lps[curLen - 1];
- } else {
- lps[index] = curLen;
- index++;
- }
- }
- }
- System.out.println("LPS of: " + pattern);
- for (int i : lps) {
- System.out.print(i + " ");
- }
- return lps;
- }
- }
Add Comment
Please, Sign In to add comment