【问题标题】:Counting the number of occurrences of a string within a string计算字符串中字符串出现的次数
【发布时间】:2014-04-24 16:58:00
【问题描述】:

计算字符串中出现的所有子字符串的最佳方法是什么?

示例:计算FooFooBarFooBarFoo 中的出现次数

【问题讨论】:

标签: c++ string counting


【解决方案1】:

一种方法是使用std::string find函数:

#include <string>
#include <iostream>
int main()
{
   int occurrences = 0;
   std::string::size_type pos = 0;
   std::string s = "FooBarFooBarFoo";
   std::string target = "Foo";
   while ((pos = s.find(target, pos )) != std::string::npos) {
          ++ occurrences;
          pos += target.length();
   }
   std::cout << occurrences << std::endl;

}

【讨论】:

  • 最坏的情况仍然是 O(N*M) ,不是吗?
  • @aseem 对我迟到的回复感到抱歉。恕我直言,标准库函数可能已经优化,它们可能使用 KMP 进行模式匹配,这是有效的。但我不是 100% 确定。
  • 重叠出现失败。
  • 没有库 fns 是 not optimized
【解决方案2】:
#include <iostream>
#include <string>

// returns count of non-overlapping occurrences of 'sub' in 'str'
int countSubstring(const std::string& str, const std::string& sub)
{
    if (sub.length() == 0) return 0;
    int count = 0;
    for (size_t offset = str.find(sub); offset != std::string::npos;
     offset = str.find(sub, offset + sub.length()))
    {
        ++count;
    }
    return count;
}

int main()
{
    std::cout << countSubstring("FooBarFooBarFoo", "Foo")    << '\n';

    return 0;
}

【讨论】:

    【解决方案3】:

    您应该为此使用 KMP 算法。 它在 O(M+N) 时间内解决它,其中 M 和 N 是两个字符串的长度。 欲了解更多信息- https://www.geeksforgeeks.org/frequency-substring-string/

    所以 KMP 算法所做的是,它搜索字符串模式。当一个模式有一个子模式在子模式中出现多个时,它使用该属性来提高时间复杂度,在最坏的情况下也是如此。

    KMP 的时间复杂度为 O(n)。 查看详细算法: https://www.geeksforgeeks.org/kmp-algorithm-for-pattern-searching/

    【讨论】:

      【解决方案4】:
      #include <iostream>
      #include<string>
      using namespace std;
      int frequency_Substr(string str,string substr)
      {
          int count=0;
          for (int i = 0; i <str.size()-1; i++)
          {
              int m = 0;
              int n = i;
              for (int j = 0; j < substr.size(); j++)
              {
                  if (str[n] == substr[j])
                  {
                      m++;
                  }
                  n++;
              }
              if (m == substr.size())
              {
                  count++;
              }
          
          }
          cout << "total number of time substring occur in string is " << count << endl;
          return count;
      }
      int main()
      {
          string x, y;
          cout << "enter string" << endl;
          cin >> x;
          cout << "enter substring" << endl;
          cin >> y;
          frequency_Substr(x, y);
          return 0;
      }
      

      【讨论】:

      • 很好,你把它编码出来了。你能否也把你的代码的一些结果
      猜你喜欢
      • 2020-02-21
      • 2012-02-12
      • 2012-10-03
      • 1970-01-01
      • 2023-02-04
      • 2012-06-24
      相关资源
      最近更新 更多