String Searching Algorithms in C++

Lesson Overview

Welcome to this insightful lesson. Today's focus will be on string searching algorithms, a fundamental part of programming often encountered in software development, the design of databases, and information retrieval. This lesson will walk you through the intricacies of these algorithms, explaining the principles behind each one.

Quick Example

For instance, consider the Knuth-Morris-Pratt (KMP) string searching algorithm, where the essence of its design is to eliminate the need to backtrack by retaining the information elicited from previous comparisons. If, at some point in the pattern, there's a mismatch, the algorithm does not begin matching the pattern with the text from the start but from a pre-computed point that takes into account all previous comparisons. It's an efficient way to avoid redoing work!

There are many details regarding this algorithm, but here is what its implementation might look like:

#include <iostream>
#include <vector>
using namespace std;

vector<int> computeLPSArray(const string& pattern) {
    vector<int> lps(pattern.size());
    int length = 0;
    lps[0] = 0;
    int i = 1;

    while (i < pattern.size()) {
        if (pattern[i] == pattern[length]) {
            length++;
            lps[i] = length;
            i++;
        } else {
            if (length != 0) {
                length = lps[length - 1];
            } else {
                lps[i] = 0;
                i++;
            }
        }
    }
    return lps;
}

int kmpSearch(const string& text, const string& pattern) {
    vector<int> lps = computeLPSArray(pattern);
    int i = 0; // index for text
    int j = 0; // index for pattern

    while (i < text.size()) {
        if (pattern[j] == text[i]) {
            i++;
            j++;
        }

        if (j == pattern.size()) {
            return i - j;
        } else if (i < text.size() && pattern[j] != text[i]) {
            if (j != 0) {
                j = lps[j - 1];
            } else {
                i++;
            }
        }
    }
    return -1;
}

int main() {
    string text = "abxabcabcaby";
    string pattern = "abcaby";
    int result = kmpSearch(text, pattern);

    if (result != -1) {
        cout << "Pattern found at index " << result << endl;
    } else {
        cout << "Pattern not found" << endl;
    }
    return 0;
}

Feel free to ask questions to clarify the details!

What's Next? Anticipate Some Practice!

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal