Sobes.tech
Junior — Middle

Have you had experience using the substring search algorithm with the Knuth-Morris-Pratt (KMP) method?

sobes.tech AI

Answer from AI

Yes, the Knuth-Morris-Pratt (KMP) algorithm is used for efficient substring search within a string with linear complexity.

The main idea of KMP is to avoid backtracking in the source string upon a mismatch, instead using information about previously matched prefixes.

Example implementation in Kotlin for Android:

fun kmpSearch(text: String, pattern: String): List<Int> {
    val lps = IntArray(pattern.length)
    computeLPSArray(pattern, lps)
    val result = mutableListOf<Int>()
    var i = 0 // index for text
    var j = 0 // index for pattern
    while (i < text.length) {
        if (pattern[j] == text[i]) {
            i++
            j++
        }
        if (j == pattern.length) {
            result.add(i - j)
            j = lps[j - 1]
        } else if (i < text.length && pattern[j] != text[i]) {
            if (j != 0) j = lps[j - 1]
            else i++
        }
    }
    return result
}

fun computeLPSArray(pattern: String, lps: IntArray) {
    var length = 0
    var i = 1
    lps[0] = 0
    while (i < pattern.length) {
        if (pattern[i] == pattern[length]) {
            length++
            lps[i] = length
            i++
        } else {
            if (length != 0) {
                length = lps[length - 1]
            } else {
                lps[i] = 0
                i++
            }
        }
    }
}

This algorithm is useful when you need to quickly find multiple occurrences of a substring within a text without re-comparing already checked characters.