计算字符串中所有子字符串出现次数的最佳方法是什么?
示例:计算Foo
FooBarFooBarFoo
的出现次数
答案 0 :(得分:8)
一种方法是使用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;
}
答案 1 :(得分: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/
答案 2 :(得分:1)
#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;
}
答案 3 :(得分:0)
#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;
}