// C++ program for Naive Pattern
// Searching algorithm
#include <bits/stdc++.h>
using namespace std;
void search(char* pat, char* txt)
{
int M = strlen(pat);
int N = strlen(txt);
/* A loop to slide pat[] one by one */
for (int i = 0; i <= N - M; i++) {
int j;
/* For current index i, check for pattern match */
for (j = 0; j < M; j++)
if (txt[i + j] != pat[j])
break;
if (j == M) // if pat[0...M-1] = txt[i, i+1, ...i+M-1]
cout << "Pattern found at index "
<< i << endl;
}
}
// Driver Code
int main()
{
char txt[] = "AABAACAADAABAAABAA";
char pat[] = "AABA";
search(pat, txt);
return 0;
}
// This code is contributed
// by Akanksha Rai
//created by hyunjin.gil
#include <bits/stdc++.h>
using namespace std;
string alphabets="ABCDEFGHIJKLMNOPQRSTUVWXYZ";
void initialize(map<char,unsigned int> & tables,const string & pattern)
{
for(int i = 0; i < alphabets.size(); ++i)
{
const char ch = alphabets[i];
tables[ch] = pattern.size();
}
}
void makeTable(map<char,unsigned int> & tables, const string & pattern)
{
//last index is pattern's length
for(int i = pattern.size()-2; i >=0; --i)
{
const char ch = pattern[i];
const int value = pattern.size() - i - 1;
if(tables[ch] > value){
tables[ch] = value;
}
}
}
vector<unsigned int> findString(map<char, unsigned int>& tables, const string& pattern, const string& str)
{
unsigned int offset = 0;
const auto patternLastIndex = pattern.size() - 1;
vector<unsigned int> matches;
while (offset <= str.size())
{
auto currentIndex = patternLastIndex;
if (currentIndex + offset > str.size())
break;
while (pattern[currentIndex] == str[currentIndex + offset])
{
if (currentIndex == 0)
{
matches.push_back(offset);
offset += 1;
break;
}
currentIndex--;
}
const char rightMostChar = str[patternLastIndex + offset];
if (tables.find(rightMostChar) != tables.end())
{
offset += tables[rightMostChar];
}
else
{
offset += pattern.size();
}
}
return matches;
}
int main() {
const string pattern = "TOOTH";
const string str = "TRUSTHARDTOOTHBRUSHES";
map<char,unsigned int> tables;
initialize(tables, pattern);
makeTable(tables, pattern);
int position = findString(tables, pattern, str);
cout << position << endl;
return 0;
}