Given a string T and a pattern P which is also a string. Find the number of occurrences of P in T.
Input
Line 1: contains string P (length is less than or equals to 10^5)
Line 2: contains the string T (length is less than or equals to 10^6)
Output
Write the number of occurrences of P in T
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define N 5000000
int Count(char T[], char P[])
{
int count = 0;
char *pos, *t;
int index;
t = &T[0];
while ((pos = strstr(T, P)) != NULL)
{
index = pos - t;
strcpy(T, T + index + 1);
count++;
}
return count;
}
int main()
{
char *T = (char *)malloc(N);
char *P = (char *)malloc(N);
fgets(P, N, stdin);
fgets(T, N, stdin);
if (P[strlen(P) - 1] == '\n')
P[strlen(P) - 1] = '\0';
if (T[strlen(T) - 1] == '\n')
T[strlen(T) - 1] = '\0';
int count = Count(T, P);
printf("%d", count);
return 0;
}
for this input, I get correct output (10) on my laptop but get 9 as output on website.
Pham Q Dung
cdefghijkmlnoPham Q Dungxyz 1234567890Pham Q Dungijkmlnopqrstuvwxyz 1234567890Pham Q Dunghijkmlnopqrstuvwxyz 1234567890Pham Q Dungfghijkmlnopqrstuvwxyz 123456789Pham Q DungefghijkmlnopqrstuvwxyzPham Q DunghijkmlnopqrstuvwxyPham Q Dung67890Pham Q DungbcdefghijkmlnopqrstuvwPham Q Dungqrstuvwxyz 1234567890Pham Q Dung
strcpy(T, T + index + 1);
Using a single overlapping string instrcpy
leads to undefined behavior. And allocating 10 million bytes for your strings? Why? Does the assignment requirement really say that, or is it just cargo cult programming? There's also no error checking, and there are better way to remove the newline afterfgets
.