KMP in Interview After some questions about basic knowledge of Java, interviewer give Amy the last question: how to find the ‘Longest common substring between two string’ efficiently? Amy thinks for a while and comes up with the DP solution which depends on the core equation of // longest common suffix dp [ i ] [ j ] = m [ i ] == n [ j ] ? dp [ i - 1 ] [ j - 1 ] + 1 : 0 max ( dp [ 1 . . x ] [ 1 . . y ] ) Interviewer check the solution and said, “It’s a good solution. But it’s time complexity is O(n^2) and space complexity is also O(n^2) . Can you come up with better algorithm?” Amy ponder the question again and suddenly the KMP algorithm dawn on her. What is KMP "The KMP algorithm is a very efficient string comparison algorithm which save the time by extra pre-process. When we compare string in common way, we do like this: when a mismatch happens, we reset start point to old_position + 1 : ...xxx...xxy xxy.. ⇑ mismatch ...xxx....
Learn programming, still on the way