Sunday, 21 July 2019

Count the number of times a character has occurred before a given index in a given string: C, C++ and Python Program

Sample Input:
11                             is length of string
aabcdbcdbcd            given string       
4                               Number of Queries
1                               we have to find the number of times character at index 1 occurred before index 1
3                               we have to find the number of times character at index 3 occurred before index 3
4                               we have to find the number of times character at index 4 occurred before index 4
5                               we have to find the number of times character at index 5 occurred before index 5


Sample Output:
1
0
0
1

In C:
#include<stdio.h>

int main()
{
 unsigned long long int n,i,q,p;
 scanf("%llu",&n);
 char st[n+1];
 scanf(" %s",st);

 scanf("%llu",&q);
 long long int h[26][500000]={{0}};

 char j;
 for(i=1;st[i]!='\0';i++)
 {
     for(j='a';j<='z';j++)
     {
         if(st[i] == j)
            

             h[st[i]-'a'][i]=h[j-'a'][i-1]+1;
         else 
            h[j-'a'][i]=h[j-'a'][i-1];
            
     }
 }

 while(q--)
 {
     scanf("%llu",&p);
     char temp=st[p-1];
     printf("%lld\n",h[temp-'a'][p-1]);
 }
}

In C++


#include <bits/stdc++.h>
using namespace std;

int main()
{
    unsigned long long int n,i,q,p;
    scanf("%llu",&n);
    char st[n+1];
    scanf(" %s",st);
    scanf("%llu",&q);
    while(q--)
    {
        scanf("%llu",&p);
        printf("%lld\n",count(st,st+p,st[p]));
    }
 

    return 0;

No comments:

Post a Comment