-6

I need to find out for example how many times test appears in ttest and answer for that would be 2, or for example world in w1o1r1l1d and answer would be one. I have already written a code which finds all possibilities, and then checks if it is the string I am searching for, but that is too slow.

niklasfi
  • 15,245
  • 7
  • 40
  • 54
Luka
  • 187
  • 3
  • 9

1 Answers1

1

I'd try a recursive solution.

The number of times a one-letter string appears in another string is the number of times that characters appears there.

the number of time "r" appears in "program" is 2

The number of times a n-letter string appears in another string is:
the number of times the (n-1)- string appears after the first match for the first letter plus the number of times the n-letter string appears after the first match

the number of times "test" appears in "ttest" is
      the number of times "est" appears in "test"
    + the number of times "test" appears in "test"

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

int count(const char *needle, const char *stack) {
  int n = 0;
  const char *p;
  if (*stack == 0) return 0;
  if (*needle == 0) return 0;
  p = strchr(stack, *needle);
  if (needle[1] == 0) n += !!p;
  if (p) {
    n += count(needle + 1, p + 1);
    n += count(needle, p + 1);
  }
  return n;
}

int main(void) {
  const char *needle, *stack;

  needle = "a"; stack = "";
  printf("[%s] exists %d times in [%s]\n", needle, count(needle, stack), stack);

  needle = ""; stack = "a";
  printf("[%s] exists %d times in [%s]\n", needle, count(needle, stack), stack);

  needle = "a"; stack = "abracadabra";
  printf("[%s] exists %d times in [%s]\n", needle, count(needle, stack), stack);

  needle = "br"; stack = "abracadabra";
  printf("[%s] exists %d times in [%s]\n", needle, count(needle, stack), stack);

  needle = "test"; stack = "ttest";
  printf("[%s] exists %d times in [%s]\n", needle, count(needle, stack), stack);

  needle = "world"; stack = "w1o1r1l1d";
  printf("[%s] exists %d times in [%s]\n", needle, count(needle, stack), stack);

  return 0;
}
pmg
  • 106,608
  • 13
  • 126
  • 198