Pattern Searching : Boyer Moore Algorithm – Bad Character Heuristic

PROBLEM :

Given a text and a pattern, Find whether the pattern exist in the text or not. If it is present print "found" without quotes else print "not found"
without quotes.

Input:
The first line of input contains an integer T denoting the number of test cases. Each test case consist of a string in 'lowercase' only in a
separate line.

Output:
Print "found" or "not found" in a separate line.

Constraints:
1 = T = 30
1 = |s| = 100


Example:
Input
1
geeksforgeeks
geeks

Output
found

--------------------------------------------------------------------------------
SIMPLE c++ IMPLEMENTATION :
--------------------------------------------------------------------------------

#include<iostream>
using namespace std;
#include<string.h>
bool Pattern_Searching_Boyer_Moore(string ,string ) ;
void BadCharecter_Table(string ,int [],int ) ;
int maxof(int ,int ) ;
int main()
 {
int t ;
string str1,str2 ;
cin>>t ;
while(t--)
{
   cin>>str1 ;
   cin>>str2 ;
 
   bool ans=Pattern_Searching_Boyer_Moore(str1,str2) ;
   if(ans)
       cout<<"found" ;
   else
       cout<<"not found" ;
   cout<<endl ;
}
return 0;
}

bool Pattern_Searching_Boyer_Moore(string str,string pattern)
{
    int l1,l2 ;
    l1=str.length() ;
    l2=pattern.length() ;
 
    int BadChar[256] ;
    BadCharecter_Table(pattern,BadChar,l2) ;
   
    int i,j ;
    i=0 ;
   
    while(i<=l1-l2)
    {
    j=l2-1 ;
    while(j>=0&&str[i+j]==pattern[j])
    j-- ;
   
    if(j<0)
    return true ;
    else
    i=i+maxof(1,j-BadChar[str[i+j]]) ;
}
    return false ;
}

void BadCharecter_Table(string str,int BadChar[],int no)
{
    int i ;
    for(i=0;i<256;i++)
    BadChar[i]=-1 ;
   
    for(i=0;i<no;i++)
    BadChar[str[i]]=i ;
}

int maxof(int a,int b)
{
return a>b?a:b ;
}

--------------------------------------------------------------------------------

Comments

Popular posts from this blog

Count ways to N'th Stair(Order does not matter)

Replace all ‘0’ with ‘5’ in an input Integer

Chocolate Distribution Problem

Remove characters from the first string which are present in the second string

Primality Test ( CodeChef Problem code: PRB01 )