题目:Palindrome
题意:给出一段字符串,求其字串中的最长的回文串、
解法:枚举回文串的中间点,再往两边搜索,时间为O(n^2)
#include <iostream>
#include <string>
using namespace std;
char s[2000];
int n = 0;
int main() {
char c;
while ((c = getchar()) != EOF && c != '\n') {
s[++n] = c;
}
int ans = 0, l = 0;
for (int i = 1; i <= n; i++) {
int x = i, y = i, t = -1;
while (x > 0 && y <= n && s[x] == s[y]) {
t += 2;
if (t > ans) {
ans = t;
l = x;
}
x--; y++;
}
x = i; y = i+1; t = 0;
while (x > 0 && y <= n && s[x] == s[y]) {
t += 2;
if (t > ans) {
ans = t;
l = x;
}
x--; y++;
}
}
for (int i = l; i <= l+ans-1; i++) cout << s[i];
cout << endl;
}