The KMP algorithm is an improved string matching algorithm proposed by, and therefore people call it the Knut-Morris-Prat operation (KMP algorithm for short). The core of the KMP algorithm is to use the information after the matching failure to minimize the number of matches between the pattern string and the main string to achieve the purpose of fast matching. The specific implementation is achieved through a next() function, which itself contains local matching information of the pattern string. The time complexity of the KMP algorithm O(m+n).
The implementation method is no longer ugly here. There are many explanations on the Internet, and here I just record the code of the C# implementation.
public class KMP { public static int[] GetNext(String ps) { char[] p = (); int[] next = new int[]; next[0] = -1; int j = 0; int k = -1; while (j < - 1) { if (k == -1 || p[j] == p[k]) { next[++j] = ++k; } else { k = next[k]; } } return next; } public static int GetIndex(String ts, String ps) { char[] t = (); char[] p = (); int i = 0; // The position of the main string int j = 0; // The position of the pattern string int[] next = GetNext(ps); while (i < && j < ) { if (j == -1 || t[i] == p[j]) { // When j is -1, the one to move is i, and of course j must also be 0 i++; j++; } else { // i does not need to go back // i = i - j + 1; j = next[j]; // j Return to the specified location } } if (j == ) { return i - j; } else { return -1; } } } //test static void Main(string[] args) { ( ("abcdbcxdbc", "dbc")); (); }
The above is the detailed content of the sample code for implementing the KMP algorithm in c#. For more information about the C# kmp algorithm, please pay attention to my other related articles!