题解 | #密码截取#
密码截取
https://www.nowcoder.com/practice/3cd4621963e8454594f00199f4536bb1
#include <iostream>
using namespace std;
int main() {
string str;
cin >> str;
int j = 0, Max1 = 1, Max2 = 1;
//情况1:左右对齐,数量为偶数
for (int i = 1; i < str.length(); ++i) {
//当满足左右对称时一直计数
while ((str[i - j - 1] == str[i + j]) && ((i + j) <= str.length() - 1) &&
(i - j - 1) >= 0) {
++j;
}
Max1 = Max1 > 2 * j ? Max1 : 2 * j;
j = 0;
}
j = 1;
//情况2:左右对齐,数量为奇数
for (int i = 1; i < str.length(); ++i) {
//当满足左右对称时一直计数
while ((str[i - j] == str[i + j]) && ((i + j) <= str.length() - 1) &&
(i - j ) >= 0) {
++j;
}
Max2 = Max2 > (2 * (j - 1) + 1) ? Max2 : (2 * (j - 1) + 1);
j = 1;
}
//两者取较大值
Max1 = Max1 > Max2 ? Max1 : Max2;
cout << Max1;
return 0;
}
// 64 位输出请用 printf("%lld")