Created
March 5, 2020 02:57
-
-
Save vtta/6ad2f5611394b6c655086c5a3f3db113 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| int kmp(string const &s, string const &p) { | |
| auto ns = s.size(), np = p.size(); | |
| if (np == 0) { | |
| return 0; | |
| } | |
| if (ns < np || ns == 0) { | |
| return -1; | |
| } | |
| vector<size_t> next(np); | |
| auto cur = 1ul, prev = 0ul; | |
| while (cur < np) { | |
| if (p[cur] == p[prev]) { | |
| // sotre the prefix length which is index + 1 | |
| next[cur] = prev + 1; | |
| // move on to next char | |
| ++cur, ++prev; | |
| } else if (prev > 0) { | |
| // still possible to find the prefix of the prefix | |
| prev = next[prev - 1]; | |
| } else { | |
| next[cur] = 0; | |
| ++cur; | |
| } | |
| } | |
| auto i = 0ul, j = 0ul; | |
| while (i < ns && j < np) { | |
| if (s[i] == p[j]) { | |
| ++i, ++j; | |
| } else if (j > 0) { | |
| j = next[j - 1]; | |
| } else { | |
| ++i; | |
| } | |
| } | |
| return i - j > ns - np ? -1 : i - j; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment