我的代码找不到了。字符串中的子字符串。为什么 j<=str.length() - 3 导致运行时错误?
My code to find no. of a substrings in a string. Why is j<=str.length() - 3 causing runtime error?
#include <iostream>
#include <string>
using namespace std;
int main() {
int T;
int count = 0;
cin>>T;
for(int i = 0; i<T; i++)
{
string str;
cin>>str;
count = 0;
这部分用于检查我的代码中出现了多少次“xyz”。
for 循环中的测试条件 j<=str.length() - 3 导致某些测试用例出错。
当我 运行 for 循环测试条件 j<=str.length() 它不会给出错误。
for(int j = 0;j<=str.length()-3; j++)
{
string x;
x = str.substr(j, 3);
if(x =="xyz")
{
count++;
}
}
if(count)
{
cout<<count<<endl;
}
else
{
cout<<"-1"<<endl;
}
}
return 0;
}
字符串长度使用无符号数学; 2-3 变成 2^64-1。尝试 j<-3 || j+3<=str.length()
#include <iostream>
#include <string>
using namespace std;
int main() {
int T;
int count = 0;
cin>>T;
for(int i = 0; i<T; i++)
{
string str;
cin>>str;
count = 0;
这部分用于检查我的代码中出现了多少次“xyz”。
for 循环中的测试条件 j<=str.length() - 3 导致某些测试用例出错。
当我 运行 for 循环测试条件 j<=str.length() 它不会给出错误。
for(int j = 0;j<=str.length()-3; j++) { string x; x = str.substr(j, 3); if(x =="xyz") { count++; } } if(count) { cout<<count<<endl; } else { cout<<"-1"<<endl; } } return 0;
}
字符串长度使用无符号数学; 2-3 变成 2^64-1。尝试 j<-3 || j+3<=str.length()