【发布时间】:2023-03-13 06:28:01
【问题描述】:
我有一个小问题。我正在解决一项编程任务,但遇到了问题。这很简单,但时间限制使它有点难。
查找子字符串的出现次数。您将获得 M - 长度 子串;要查找的子字符串,N - 基本字符串的长度;根据 字符串。
M N输入
10
budsvabbud
79
uaahskuskamikrofonubudsvabbudnebudlabutkspkspkspmusimriesitbudsvabbudsvabbudnel输出
3
我尝试使用内置函数find,但速度不够:
#include<iostream>
#include<string>
using namespace std;
int main()
{
int n;
int occurrences = 0;
string::size_type start = 0;
string base_string, to_find;
cin >> n >> to_find >> n >> base_string;
while ((start = base_string.find(to_find, start)) != string::npos) {
++occurrences;
start++;; // see the note
}
cout << occurrences << endl;
}
所以我尝试编写自己的函数,但速度更慢:
#include<iostream>
#include<cstdio>
#include<string>
#include<queue>
using namespace std;
int main()
{
int n, m;
string to_find;
queue<int> rada;
int occurrences = 0;
cin >> m >> to_find >> n;
for (int i = 0; i < n; i++)
{
char c;
scanf(" %c", &c);
int max = rada.size();
for (int j = 0; j < max; j++)
{
int index = rada.front();
rada.pop();
if (c == to_find[index])
{
if (++index == m) {
occurrences++;
}
else
rada.push(index);
}
}
if (c == to_find[0])
{
if (1 == m)
n++;
else
rada.push(1);
}
}
cout << occurrences << endl;
}
我知道有些人在 0 毫秒内完成了这项工作,但我的第一个代码需要超过 2000 毫秒,而第二个代码则要多得多。你有什么想法如何解决这个问题吗? 谢谢。
编辑: 长度限制:
M
N
【问题讨论】:
-
2000 毫秒!输入多长时间?
-
@HumamHelfawi 抱歉,我忘记写了。我将编辑我的问题。
-
你启用优化了吗?你真的是说 2000 毫秒吗?我会惊讶于即使是调试构建也需要这么长时间。
-
对于大文件中的快速搜索,像 Boyer-Moore 之类的东西可能要快一个数量级(或更多) - 但对于 79 个字符来说,它可能不值得。
-
是的,我的意思是 2000 毫秒。但不是为了输入我举的例子。可能有长度为 200 000 的输入。
标签: c++ string performance find find-occurrences