#include <iostream>
using namespace std;
int main()
{
//code
int test;
cin >> test;
while(test--)
{
int count = 0;
string input;
cin >> input;
for (int j = 0; j < input.length() - 2; j++)
{
if (input.substr(j, 3) == "gfg")
{
count +=1;
}
}
if (count > 0)
{
cout << count << endl;
}
else
{
cout << -1 << endl;
}
}
return 0;
}
这段代码显示中止信号从中止(3)(SIGABRT),同时提交在极客为极客,而运行在本地计算机上完美,甚至在各种在线编译器上完美。 想不出这个问题。 有人能帮忙吗?
想一想当input
少于两个字符时会发生什么。
input.length()
是一个无符号的量,因此input.length()-2
会绕到一个天文数字。
当j
是一个天文数字时,input.substr(j,3)
效果不好:它抛出异常std::OUT_OF_RANGE
; 由于没有捕捉到此异常,程序将终止。
这些竞赛测试是否覆盖了所有可能的输入域,特别是边缘情况。 在编写算法时一定要考虑到它们。
我认为。substr需要字符串库。 出于某种原因,你不需要它在本地。
尝试添加
#include <string>
编辑:我尝试了一些变体
if(input.length()<2)
{
cout<<-1<<"\n" ;
break;
}
for循环应该帮助(input.length()在减去比它的值更多的值时不会溢出。