All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.zodiac.algorithms.strings.KnuthMorrisPratt Maven / Gradle / Ivy

package org.zodiac.algorithms.strings;

import java.util.ArrayList;
import java.util.List;

/**
 * This class implements KMP algorithm for finding length of maximal prefix-suffix for each prefix of the string.
 * Prefix-suffix of string S is a substring which occurs at the beginning and at the end of S.
 * 

* Time complexity: O(n)
*

* @see Knuth Morris Pratt (Wikipedia) *
* */ public abstract class KnuthMorrisPratt { private KnuthMorrisPratt() {} /** * This function implements KMP algorithm for finding length of maximal prefix-suffix for each prefix of the string. * Prefix-suffix of string S is a substring which occurs at the beginning and at the end of S. *

* @param text Text * @return maximal length of prefix-suffix for each prefix of the string text */ public static List getPrefSufTable(String text) { final List prefSufTable = new ArrayList(); final char[] chars = text.toCharArray(); if (text.length() == 0) return prefSufTable; prefSufTable.add(0); for (int i = 1; i 0 && (chars[i] != chars[sizeOfPrefSuf])) /*Because string is 0-indexed.*/ sizeOfPrefSuf = prefSufTable.get(sizeOfPrefSuf-1); /* * If characters at this positions are different then sizeOfPrefSuf is equal to zero, * so there is no proper prefix-suffix. * */ if (chars[i] == chars[sizeOfPrefSuf]) { prefSufTable.add(sizeOfPrefSuf+1); } else { prefSufTable.add(0); } } return prefSufTable; } }





© 2015 - 2025 Weber Informatics LLC | Privacy Policy