跳至主要内容

Understand KMP

KMP wiki introduciton

The core thought behind the complex description is avoiding duplicate comparison. For example:

    aim:    ababababd
            ^   ^
            s   i
pattern:    ababd
                ^
                j

When aim[i] != pattern[j], what brute-force solution usually do is set i = s + 1; j = 0 to re-compare it. But actually, we already know aim[s + 1] == pattern[1] && pattern[1] != pattern[0], so this comparison will always fail. So if there any way to avoid this? kmp algorithm use a pre-processed array – next to handle this.

What does next mean

Back to upper example, if we using kmp to compare and fail the comparison, i will remain not changed, j = next[j];//2 in this case.

    aim:    ababababd
            ^   ^
            s   i
pattern:      ababd
                ^
                j

So what on earth the next is?
We try to understand it by example:

        ------------------------
aim         |/////|y|  |/////|z|    
        ------------------------
                              ^
                              i
            -------------------
pattern     |/////|y|  |/////|x|    
            -------------------
            ^      ^   ^      ^
            0      k   jj     j

Again, the we compare aim[i] and pattern[j] and fail to match. We can move pattern right by j = k; //k == next[j] if we know [0, k) == [jj, j). So the core of next array is the same sub-string in pattern. Actually, it has to be prefix and suffix( from start to current index.)

In conclusion, next can be understood by this two views:

  • how it come: longest common prefix/suffix
  • how it used: next position to compare & how many chars to skip
Some example to make sure you understand:
string next[4]
aaaa 2
aaab 2

So how next is computed?

Using dynamic programming: compute next[i] from next[i-1].

-----------------------
|/////|x|y|  |/////|x|y|  
-----------------------
^        ^          ^ ^
0        k            i

next[i-1] = k
if p[i] == p[k]
    next[i] = next[i-1] + 1
else 
    ???

The difficult part is what to do when next char not equal? Let’s see a larger example:

--------------------------------------------------
|/////|z|  |/////|y|        |/////|z|  |/////|z|  
--------------------------------------------------
       ^   ^      ^         ^          ^      ^
      k0  i2      k         i0        i1      i


p[k] != p[z]// so we have to find a shorter prefix/suffix
// Assume we finally find a k0, make
[0, k0) == [i1, i)

// So we can find a same sub-string in [i2, k), because
[0, k) == [i0, i)
// now:
[0, k0) == [i2, k)
// i.e. it is a common prefix/suffix for index k
// because next is longest common prefix/suffix,
// k0 must <= next[k]

So we can complete upper pseudo-code:

if p[i] == p[k]
    next[i] = next[i-1] + 1
else 
    k = next[k] and try again

Full source can be found in gist

Ref

  1. A blog in chinese
  2. Wikipedia
  3. Gist cpp code
  4. Application in a problem

Written with StackEdit.

评论

此博客中的热门博文

Spring Boot: Customize Environment

Spring Boot: Customize Environment Environment variable is a very commonly used feature in daily programming: used in init script used in startup configuration used by logging etc In Spring Boot, all environment variables are a part of properties in Spring context and managed by Environment abstraction. Because Spring Boot can handle the parse of configuration files, when we want to implement a project which uses yml file as a separate config file, we choose the Spring Boot. The following is the problems we met when we implementing the parse of yml file and it is recorded for future reader. Bind to Class Property values can be injected directly into your beans using the @Value annotation, accessed via Spring’s Environment abstraction or bound to structured objects via @ConfigurationProperties. As the document says, there exists three ways to access properties in *.properties or *.yml : @Value : access single value Environment : can access multi

Elasticsearch: Join and SubQuery

Elasticsearch: Join and SubQuery Tony was bothered by the recent change of search engine requirement: they want the functionality of SQL-like join in Elasticsearch! “They are crazy! How can they think like that. Didn’t they understand that Elasticsearch is kind-of NoSQL 1 in which every index should be independent and self-contained? In this way, every index can work independently and scale as they like without considering other indexes, so the performance can boost. Following this design principle, Elasticsearch has little related supports.” Tony thought, after listening their requirements. Leader notice tony’s unwillingness and said, “Maybe it is hard to do, but the requirement is reasonable. We need to search person by his friends, didn’t we? What’s more, the harder to implement, the more you can learn from it, right?” Tony thought leader’s word does make sense so he set out to do the related implementations Application-Side Join “The first implementation

Implement isdigit

It is seems very easy to implement c library function isdigit , but for a library code, performance is very important. So we will try to implement it and make it faster. Function So, first we make it right. int isdigit ( char c) { return c >= '0' && c <= '9' ; } Improvements One – Macro When it comes to performance for c code, macro can always be tried. #define isdigit (c) c >= '0' && c <= '9' Two – Table Upper version use two comparison and one logical operation, but we can do better with more space: # define isdigit(c) table[c] This works and faster, but somewhat wasteful. We need only one bit to represent true or false, but we use a int. So what to do? There are many similar functions like isalpha(), isupper ... in c header file, so we can combine them into one int and get result by table[c]&SOME_BIT , which is what source do. Source code of ctype.h : # define _ISbit(bit) (1 << (