题解 | #密码截取#
密码截取
https://www.nowcoder.com/practice/3cd4621963e8454594f00199f4536bb1?tpId=37&tags=&title=&difficulty=0&judgeStatus=0&rp=1&sourceUrl=%2Fexam%2Foj%2Fta%3Fpage%3D1%26tpId%3D37%26type%3D37
/*
思路:采用中心扩展法
注意点:
1. 注意上下边界的判断
2. 注意两种回文中心的处理
*/
#include<iostream>
#include<string>
#include<algorithm>
using namespace std;
int main() {
string s;
while (cin >> s) {
int maxlen = 0;
int len = s.length();
for (int i = 1; i < len; i++) //每个点都可以为中心
{
//计算以i-1和i为中心的偶数长度的回文子串长度
int low = i - 1, high = i;
while (low >= 0 && high < len && s[low] == s[high]) { //中心两边必须都相同
low--;
high++;
}
maxlen = max(maxlen, high - low - 1);
//计算以i为中心的奇数长度的回文子串长度
low = i - 1, high = i + 1;
while (low >= 0 && high < len && s[low] == s[high]) { //中心两边必须都相同
low--;
high++;
}
maxlen = max(maxlen, high - low - 1);
}
cout << maxlen << endl;
}
return 0;
}
查看19道真题和解析
