Tuesday, February 28, 2017



Pattern count

Given a string, your task is to find the number of patterns of form 1[0]1 where [0] represents any number of zeroes (minimum requirement is one 0) there should not be any other character except 0 in the [0] sequence.

Example:
Input:
100001abc101
1001ab010abc01001
10101010

Output:
2
2
3

Check my geeksforgeeks submissionhttp://www.practice.geeksforgeeks.org/viewSol.php?subId=1574505&pid=1598

Answer 1: (Unoptimized)
#include <stdio.h>

int main(void)
{
char buff[32];
int count = 0, i = 0, zflag = 0,oflag = 0;

printf("String: ");
scanf("%s",buff);

while(buff[i] != '\0') {
if(buff[i] == '0') {
if(oflag == 1) {
oflag = 0;
zflag = 1;
}
}
else if(buff[i] == '1') {
oflag = 1;
if(zflag == 1) {
//oflag = 0;
zflag = 0;
count++;
}
}
else {
oflag = 0;
zflag = 0;
}
i++;
}
printf("Count = %d\n",count);

return 0;
}

Answer2: (Better version)
#include <stdio.h>
#include <string.h>

int patterncount(char *s)
{
int len = strlen(s), i, count = 0;

for(i = 0; i < len; i++) {
if(s[i] == '1' && s[i+1] == '0') {
i++;
for(; i < len; i++) {
if(s[i] == '1') {
count++;
i--;
break;
}
else if (s[i] != '0')
break;
}
}
}
return count;
}

int main(void)
{
char buff[32];

printf("String: ");
scanf("%s", buff);

printf("Count = %d\n",patterncount(buff));

return 0;
}