Sunday 19 October 2014

Count occurences of pattern string

Level: Medium

Given a source string S and a pattern string P, count the number of times the pattern string P occurs in the source string S. 
Note: Overlapping sequences are counted as separate occurrences. 

Input Format:
First line is the source string S s.t. 1 <= |S| <= 8192 characters
Second line is the pattern string P s.t. 1 <= |P| <= 8192 characters

Output Format:
Output a single integer containing the number of occurrences of pattern string P in source string S.





#include<stdio.h>
#include<string.h>

int main()
{char st[8192],sb[8192];
scanf("%s",&st);
scanf("%s",&sb);
int a,b,c=0,d=0,i,j;

a=strlen(st);
b=strlen(sb);

for(i=0;i<a;i++)
{
if(st[i]==sb[0])
{c=0;
   for(j=0;j<b;j++)
   {
   if(sb[j]==st[i+j])
   {c++;}}
   if(c==b)
   d++;
   }
   }
   printf("%d",d);
   }

2 comments:

  1. Replies
    1. What to explain in this . This is very simple and compact code

      Delete