我会尝试递归解决方案。
一个字母的字符串出现在另一个字符串中的次数是字符出现在那里的次数。
the number of time "r" appears in "program" is 2
一个n字母字符串在另一个字符串中出现的次数是:
(n-1)- 字符串在第一个字母的第一次匹配后出现的次数加上第一次匹配后 n 字母字符串出现的次数
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;
}