Monday 22 December 2014

Problem Count Occurences of pattern in a string

Count occurences of pattern string[C Program]

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.

Example:
Input:     mississippi
         issi
Output:  2



Program:

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

int main(){
 char str[8192],pstr[8192];
 int cnt=0,t,oc=0;
 scanf("%s",str);
 scanf("%s",pstr);
 for(int i=0;i<strlen(str);i++){
      t=i;
      for(int j=0;j<strlen(pstr);j++){
           if(str[t]==pstr[j]){
              cnt++; 
              t++;
           }else{
              break;
           }
      }
      if(cnt==strlen(pstr)){                 
            oc++;
      }
      cnt=0;
 }
 printf("%d",oc);
 return 0;
}

-------X----------X----------X----------X----------X----------X----------X-------

1.Input:     mississippi
           issi
   Output:  2
2.Input:     ouagadougou
           ou
   Output:  3
3.Input:     banana
           ana
   Output:  2


0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home