题解 | #密码截取#
密码截取
https://www.nowcoder.com/practice/3cd4621963e8454594f00199f4536bb1
#include <iostream>
#include <string>
using std::cout;
using std::endl;
using std::cin;
using std::string;
void test() {
string str;
cin >> str;
int max_length = 0;
int max_start = 0;
int max_end = 0;
int n = str.size();
for (int i = 0; i < n; i++) {
// 找到以当前字符为中心的奇数长度回文
int left = i, right = i;
while (left >= 0 && right < n && str[left] == str[right]) {
if ((right - left + 1) > max_length) {
max_length = right - left + 1;
max_start = left;
max_end = right;
}
left--;
right++;
}
// 找到以当前字符和下一个字符为中心的偶数长度回文
left = i;
right = i + 1;
while (left >= 0 && right < n && str[left] == str[right]) {
if ((right - left + 1) > max_length) {
max_length = right - left + 1;
max_start = left;
max_end = right;
}
left--;
right++;
}
}
cout << max_length << endl;
// cout << "max_start = " << max_start << endl;
// cout << "max_end = " << max_end << endl;
// cout << str.substr(max_start, max_length) << endl;
}
int main(int argc, char* argv[]) {
test();
return 0;
}
查看14道真题和解析
