Skip to content

Commit 942ca76

Browse files
authored
Create naive_pattern_matching.cpp
Given text string with length n and a pattern with length m, the task is to prints all occurrences of pattern in text.
1 parent 136e6c0 commit 942ca76

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

strings/naive_pattern_matching.cpp

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
#include <iostream>
2+
#include <string>
3+
using namespace std;
4+
5+
void search(string& pat, string& txt) {
6+
int M = pat.size();
7+
int N = txt.size();
8+
9+
// A loop to slide pat[] one by one
10+
for (int i = 0; i <= N - M; i++) {
11+
int j;
12+
13+
// For current index i, check for pattern match
14+
for (j = 0; j < M; j++) {
15+
if (txt[i + j] != pat[j]) {
16+
break;
17+
}
18+
}
19+
20+
// If pattern matches at index i
21+
if (j == M) {
22+
cout << "Pattern found at index " << i << endl;
23+
}
24+
}
25+
}
26+
27+
// Driver's Code
28+
int main() {
29+
// Example 1
30+
string txt1 = "AABAACAADAABAABA";
31+
string pat1 = "AABA";
32+
cout << "Example 1: " << endl;
33+
search(pat1, txt1);
34+
35+
// Example 2
36+
string txt2 = "agd";
37+
string pat2 = "g";
38+
cout << "\nExample 2: " << endl;
39+
search(pat2, txt2);
40+
41+
return 0;
42+
}

0 commit comments

Comments
 (0)