题解 | #密码截取#
密码截取
https://www.nowcoder.com/practice/3cd4621963e8454594f00199f4536bb1
#include <cstddef>
#include <iostream>
#include <string>
#include <list>
using namespace std;
int main() {
string encrypted_str;
cin >> encrypted_str;
size_t encrypted_str_len = encrypted_str.size();
/* 最大的对称字符串长度 */
int max_symetric_len = 0;
/* 当字符串长度为1,则最长是1 */
if (encrypted_str_len == 1) {
max_symetric_len = 1;
} else if (encrypted_str_len == 2) {
/* 当字符串长度为2 */
if (encrypted_str[0] == encrypted_str[1]) {
/* 当字符串2个字符相同,则最长是2 */
max_symetric_len = 2;
} else {
/* 当字符串2个字符不相同,则最长是1 */
max_symetric_len = 1;
}
} else {
/* 存储所有对称字串的长度 */
list<int> symetric_len_list;
/* 情况1:ABA 有一个字符,其两边字符相等,据此尽可能向两边扩撒,因此长度为奇数 */
for (int i = 1 ; i < encrypted_str_len - 1; i++) {
if (encrypted_str[i - 1] == encrypted_str[i + 1]) {
/* 此种情况,最大长度从3开始计算,向两边扩展 */
int symetric_len = 3;
/* 注意,这里向两边扩展时,需要保证下标在字符串范围内 */
for (int offset = 2; (i - offset >= 0) &&
(i + offset < encrypted_str_len); offset++) {
if (encrypted_str[i - offset] == encrypted_str[i + offset]) {
/* 注意,向两边扩展时,成对出现需要+2 */
symetric_len+=2;
/* 注意,当扩展到字符串边界时,需要手动添加到 symetric_len_list */
if(i - offset == 0 || i + offset == encrypted_str_len - 1){
symetric_len_list.push_back(symetric_len);
}
} else {
/* 当扩展失败时,先记录到symetric_len_list,然后打破循环,开始以后一个字符为中心开始遍历 */
symetric_len_list.push_back(symetric_len);
break;
}
}
}
}
/* 情况2:ABBA 有一个字符,其和后一个字符相等,据此向两边尽可能扩散,因此长度为偶数 */
for (int i = 0 ; i < encrypted_str_len - 1; i++) {
if (encrypted_str[i] == encrypted_str[i + 1]) {
/* 此种情况,最大长度从3开始计算,向两边扩展 */
int symetric_len = 2;
/* 注意,这里向两边扩展时,需要保证下标在字符串范围内 */
for (int offset = 1; (i - offset >= 0) &&
(i + 1 + offset < encrypted_str_len); offset++) {
if (encrypted_str[i - offset] == encrypted_str[i + 1 + offset]) {
/* 注意,向两边扩展时,成对出现需要+2 */
symetric_len+=2;
/* 注意,当扩展到字符串边界时,需要手动添加到 symetric_len_list */
if(i - offset == 0 || i + 1 + offset == encrypted_str_len - 1){
symetric_len_list.push_back(symetric_len);
}
} else {
/* 当扩展失败时,先记录到symetric_len_list,然后打破循环,开始以后一个字符为中心开始遍历 */
symetric_len_list.push_back(symetric_len);
break;
}
}
}
}
/* 对所有对称字串长度进行排序,C++ list 容器的 sort 函数默认从小到大排序 */
symetric_len_list.sort();
/* 选取最大值 */
max_symetric_len = symetric_len_list.back();
}
cout << max_symetric_len;
}
// 64 位输出请用 printf("%lld")

