So I Wrote A Backward Version Of KMP Algorithm In C# That Searches String From Right
Algorithms
2
Posts
2
Posters
3
Views
1
Watching
-
public static int LastIndexOf(this IReadOnlyList s, IReadOnlyList t, int startIndex, IEqualityComparer comparer) where T : IEquatable { Validate(s, t, startIndex); // Follow the behavior of string.LastIndexOf(string) method. if (t.Count == 0) return 0; if (s.Count == 0 || s.Count < t.Count) return -1; if (comparer == null) comparer = EqualityComparer.Default; if (t.Count == 1) return LastIndexOf(s, t\[0\], startIndex, comparer); var table = BuildTable(t, comparer); var i = 0; while (startIndex - i >= 0) { if (comparer.Equals(t\[t.Count - i - 1\], s\[startIndex - i\])) { if (i == t.Count - 1) return startIndex - t.Count + 1; i++; } else { if (table\[i\] > -1) { startIndex -= i; i = table\[i\]; } else { startIndex--; i = 0; } } } return -1; }
Full source code can be seen here[^]. The method works like
String.LastIndexOf
which searches string from the last character. TheBuildTable
method is exactly same with normal KMP algorithm. I'm not sure if this is the best solution though. -
public static int LastIndexOf(this IReadOnlyList s, IReadOnlyList t, int startIndex, IEqualityComparer comparer) where T : IEquatable { Validate(s, t, startIndex); // Follow the behavior of string.LastIndexOf(string) method. if (t.Count == 0) return 0; if (s.Count == 0 || s.Count < t.Count) return -1; if (comparer == null) comparer = EqualityComparer.Default; if (t.Count == 1) return LastIndexOf(s, t\[0\], startIndex, comparer); var table = BuildTable(t, comparer); var i = 0; while (startIndex - i >= 0) { if (comparer.Equals(t\[t.Count - i - 1\], s\[startIndex - i\])) { if (i == t.Count - 1) return startIndex - t.Count + 1; i++; } else { if (table\[i\] > -1) { startIndex -= i; i = table\[i\]; } else { startIndex--; i = 0; } } } return -1; }
Full source code can be seen here[^]. The method works like
String.LastIndexOf
which searches string from the last character. TheBuildTable
method is exactly same with normal KMP algorithm. I'm not sure if this is the best solution though.