跳至主要内容

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...

LevelDB Source Reading (4): Concurrent Access

In this thread, we come to the issue of concurrent access of LevelDB. As a database, it can be concurrently accessed by users. But, it wouldn’t be easy to provide high throughput under product load. What effort does LevelDB make to achieve this goal both in design and implementation? Goal of Design From this github issue , we can see LevelDB is designed for not allowing multi-process access. this (supporting multiple processes) doesn’t seem like a good feature for LevelDB to implement. They believe let multiple process running would be impossible to share memory/buffer/cache, which may affect the performance of LevelDB. In the case of multiple read-only readers without altering the code base, you could simply copy the file for each reader. Yes, it will be inefficient (though not on file systems that dedupe data), but then again, so would having multiple leveldb processes running as they wouldn’t be able to share their memory/buffer/etc. They achieve it by adding a l...

LevelDB Source Reading (1): Structure

LevelDB Source Reading (1): Structure LevelDB “is an open source on-disk key-value store.” After I read some documents, I have some basic understanding of LevelDB. So I come up with some questions about structure of LevelDB to answer when reading the source code. Structure Log File: repair/recover db A log file (*.log) stores a sequence of recent updates. Each update is appended to the current log file. The log file contents are a sequence of 32KB blocks. The only exception is that the tail of the file may contain a partial block. Block format: Each block consists of a sequence of records: block := record* trailer? record := checksum: uint32 // crc32c of type and data[] ; little-endian length: uint16 // little-endian type: uint8 // One of FULL, FIRST, MIDDLE, LAST data: uint8[length] // data is LengthPrefixedSlice with type from batch data definition in Block : data: also named `writeBatch` in levelDB // WriteBatch header has an 8-byte ...