题解 | #密码截取#
密码截取
https://www.nowcoder.com/practice/3cd4621963e8454594f00199f4536bb1
#include <iostream> using namespace std; int main() { string str; cin >> str; int odd_str = 1, even_str = 0; for(int i = 1; i < str.length() - 1; i++){//情况1:有效密码串长度为奇数 int odd_cur_count = 1;//记录当前有效密码串长度 int left = i - 1, right = i + 1; while(left >= 0 && right < str.length()){ if(str[left] == str[right]){ odd_cur_count += 2; left--; right++; } else break; } odd_str = max(odd_str, odd_cur_count); } for(int i = 0; i < str.length() - 1; i++){//情况2:有效密码串长度为偶数 int even_cur_count = 0; int left = i, right = i + 1; while(left >= 0 && right < str.length()){ if(str[left] == str[right]){ even_cur_count += 2; left--; right++; } else break; } even_str = max(even_str, even_cur_count); } cout << max(odd_str, even_str) << endl; return 0; }