diff --git a/problems/0028.实现strStr.md b/problems/0028.实现strStr.md index 629ff014..bf4ad600 100644 --- a/problems/0028.实现strStr.md +++ b/problems/0028.实现strStr.md @@ -1358,6 +1358,72 @@ impl Solution { } ``` +>前缀表统一不减一 +```C# +public int StrStr(string haystack, string needle) +{ + if (string.IsNullOrEmpty(needle)) + return 0; + + if (needle.Length > haystack.Length || string.IsNullOrEmpty(haystack)) + return -1; + + return KMP(haystack, needle); +} + +public int KMP(string haystack, string needle) +{ + int[] next = GetNext(needle); + int i = 0, j = 0; + while (i < haystack.Length) + { + if (haystack[i] == needle[j]) + { + i++; + j++; + } + if (j == needle.Length) + return i-j; + else if (i < haystack.Length && haystack[i] != needle[j]) + if (j != 0) + { + j = next[j - 1]; + } + else + { + i++; + } + } + return -1; +} + +public int[] GetNext(string needle) +{ + int[] next = new int[needle.Length]; + next[0] = 0; + int i = 1, j = 0; + while (i < needle.Length) + { + if (needle[i] == needle[j]) + { + next[i++] = ++j; + } + else + { + if (j == 0) + { + next[i++] = 0; + } + else + { + j = next[j - 1]; + } + } + } + return next; +} +``` +