Pattern Searching using C++ library
Last Updated :
03 May, 2023
Given a text txt[0..n-1] and a pattern pat[0..m-1], write a function that prints all occurrences of pat[] in txt[]. You may assume that n > m.
Examples:
Input : txt[] = "geeks for geeks"
pat[] = "geeks"
Output : Pattern found at index 0
Pattern found at index 10
Input : txt[] = "aaaa"
pat[] = "aa"
Output : Pattern found at index 0
Pattern found at index 1
Pattern found at index 2
The idea is to use find() in C++ string class.
CPP
#include <bits/stdc++.h>
using namespace std;
void printOccurrences(string txt, string pat)
{
int found = txt.find(pat);
while (found != string::npos) {
cout << "Pattern found at index " << found << endl;
found = txt.find(pat, found + 1);
}
}
int main()
{
string txt = "aaaa", pat = "aa";
printOccurrences(txt, pat);
return 0;
}
|
Output:
Pattern found at index 0
Pattern found at index 1
Pattern found at index 2
Time and Space Complexity:
The given program uses the string find() function to find all occurrences of a pattern in a text. The find() function returns the index of the first occurrence of the pattern in the text, or string::npos if the pattern is not found. The program repeatedly calls the find() function with an updated starting index until all occurrences of the pattern are found.
The time complexity of the program is determined by the time complexity of the find() function, which is O(NM), where N is the length of the text and M is the length of the pattern. In the worst case, the program may need to call the find() function for every substring of length M in the text, resulting in a time complexity of O(NM^2).
The space complexity of the program is determined by the space used to store the text and pattern strings. In addition, the program uses some local variables for indexing and temporary storage, but their space usage is negligible compared to the input strings. Therefore, the space complexity of the program is O(N+M), where N and M are the lengths of the text and pattern strings, respectively.
Overall, the program is efficient for finding all occurrences of a pattern in a small to medium-sized text. However, for large texts, the time complexity of the program may become a bottleneck, and more advanced string matching algorithms, such as the Knuth-Morris-Pratt algorithm or the Boyer-Moore algorithm, may be more appropriate.
Please Login to comment...