c++ - 优化算法以查找字符串的多个特定子字符串
问题描述
我是 C++ 编码的新手,刚刚开始解决竞争性编程问题。我想解决以下任务:https://onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=1620。
我想找到一个字符串的子字符串。问题是下面的代码很慢,我通过“超出时间限制”“错误”导致提交失败。我能做些什么来加快代码速度?
#include <iostream>
#include <sstream>
#include <stdio.h>
#include <string.h>
using namespace std;
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
stringstream ss;
string m;
char prob[100000];
char substring[1000];
int howManyCases = 0;
int numberOfTests = 0;
cin >> numberOfTests;
cin.ignore();
while(numberOfTests--)
{
cin >> prob >> howManyCases;
while(howManyCases--)
{
cin >> substring;
if (strstr(prob,substring)) {
ss << 'y' << "\n";
}
else
{
ss << 'n' << "\n";
}
}
}
m = ss.str();
cout << m;
return 0;
}
解决方案
我会让你成为<algorithm>
标题:
std::string parent_string = "some string lala";
std::string sub_string = "lala";
auto found = parent_string.find(sub_string);
它将迭代器返回到子字符串所在的位置。然后我会使用这个子句:
if (found != std::string::npos) std::cout << "y\n";
else std::cout << "n\n";
如果对标准库的使用没有限制,使用它总是比创建自己的算法(可能无法处理一些你不会想到的特殊情况)更好的选择。另外,将那些巨大的丑陋c-style arrays
换成std::string
.
推荐阅读
- google-chrome - 浏览器缓存的最大文件大小
- php - NSE API 为每个 API 返回 NULL 值
- flutter - 使用brave浏览器调试flutter web app
- excel - 完成刷新后关闭 Excel - ms Access 中的 VBA
- flutter - Flutter 中来自多个 FutureBuilder 的数据
- android - 当另一个活动处于画中画模式时,有什么方法可以杀死一个活动?
- r - 仅在使用 dplyr::summarise 时保留自定义错误消息
- python - python中的几何库
- python - 如何使用带有DSN服务器而不是主机/端口的python包sqlalchemy连接到ibm_db2数据库
- cql - 通过 Confluence API 获取包含字符串的文本标题的文档?