这是我的代码,试图用C++解决一个问题,该问题决定了一行中字符的子字符串的最大长度。示例输入:ATTCGGGA
|输出:3
我在终端中运行时得到的错误是:
what(): basic_string::at: __n (which is 9) >= this->size() (which is 9)
#include <bits/stdc++.h>
#include <iostream>
#include <limits.h>
using namespace std;
int main(){
string n;
cin >> n;
int length = sizeof(n);
int tempCount = 1;
int answer;
int x = 0;
while (x < length) {
if (n.at(x) == n.at(x+1)) {
tempCount += 1;
} else tempCount = 1;
if (tempCount > answer) {
answer = tempCount;
}
x++;
}
cout << answer << endl;
}
这样更改长度:
int length = n.length();
在while循环中,这一行是错误的:
if (n.at(x) == n.at(x+1)
aaaaa
的长度为5,最大索引为4。但在while循环中,当x是4时,最后一个循环,x+1是5。但你们并没有第五指数。你一定是这样的:
while(x < length - 1)
我的英语不好。我试图解释:(
在这个循环中:
while (x < length) {
if (n.at(x) == n.at(x+1)) {
您正在访问x+1
,对于最后一个x
,它超出了的范围
好消息是,在2020年,您不再需要使用length()
、at()
等。只需使用
for(auto x: n)
以下是您的操作方法:
int main() {
string n;
cin >> n;
int tempCount(0);
int answer(0);
char prev(0);
for (auto x : n) {
if (x == prev) {
++tempCount;
}
else {
prev = x;
tempCount = 1;
}
if (tempCount > answer) {
answer = tempCount;
}
}
cout << answer << endl;
}
这是我的固定代码,它做到了它的目的,感谢大家的输入。我尽力使用代码中的反馈:(:
#include <bits/stdc++.h>
#include <iostream>
#include <limits.h>
using namespace std;
int main(){
string n;
cin >> n;
int length = n.length();
int tempCount = 1;
int answer = 0;
int x = 0;
while (x < length - 1) {
if (n.at(x) == n.at(x+1)) {
tempCount += 1;
if (tempCount > answer) {
answer = tempCount;
}
} else tempCount = 1;
x++;
}
if (answer > 0){
cout << answer << endl;
} else cout << 1 << endl;
return 0;
}