【问题标题】:How to calculate how many times a string appears in another string? [duplicate]如何计算一个字符串在另一个字符串中出现的次数? [复制]
【发布时间】:2014-05-26 23:11:47
【问题描述】:

例如,我需要找出 test 出现在 ttest 中的次数,答案是 2,或者例如 worldw1o1r1l1d 中,答案是一个。我已经写了一个找到所有可能性的代码,然后检查它是否是我正在搜索的字符串,但这太慢了。

【问题讨论】:

  • 你能分享你的代码吗?你是如何衡量它太慢的......
  • 没有看到你的代码,没有人知道如何改进它......
  • 你选择了哪种语言来实现这个。
  • 第一次没有人回答您的问题并不意味着您应该再次发布。

标签: c++ string algorithm substring infix-notation


【解决方案1】:

我会尝试递归解决方案。

一个字母的字符串出现在另一个字符串中的次数是字符出现在那里的次数。

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;
}

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2014-11-14
  • 2011-07-01
  • 2011-07-13
  • 1970-01-01
  • 1970-01-01
  • 2021-10-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多