I can't understand how KMP maintains O(m+n). I'm looking for a pattern "aaaab" in "aaaaaaaaaa...".
- pattern : aaaab (length n)
- string : aaaaaaaaaa... (length m)
Then the prefix table would be
aaaab
01230
Every time mismatch happens on 'b', it's prefix length is always 0. So the pattern shifts only one step right.
aaaaaaaaaa...
aaaab
aaaaaaaaaa...
_aaaab
aaaaaaaaaa...
__aaaab
And for every trial, I need to compare full n times since mismatch happens at the very last 'b'. Thus it still requires O(m*n) comparisons.
Can anyone explain how KMP get O(m+n) for me? Thanks in advance.