回文串要添加一些辅助字符#,就是在字符串之间添加#这个辅助字符,目前这种做法主要的一个优化是 比如asbsa这个字符串。如果左边的s的回文序列求出来了,右边的s可以根据左边的s来求
int p(char*str, int n) {
if (n <= 1) {return n;
}
int newN = 2 * n + 1;
char*newstr = new char[newN];
for (int i = 0; i <newN-1; i+=2) {
newstr[i] = '#';
newstr[i+1] = str[i >> 1]; //错误2
}
newstr[newN - 1] = '#';
int*count = new int[newN];
int max = -1;
int mid = -1;
int right = -1;
for (int i = 0; i < newN; ++i) {
if (i + max >= newN) {
break;
}
int c = 0;
if (mid != -1 && i < right) {
int left = (mid << 1) - i;
c = count[left];
}
while ((i + c + 1) < newN && (i - c - 1) >= 0) {
if (newstr[i + c + 1] == newstr[i - c - 1])
++c;
else
break;
}
count[i] = c;
if (max == -1 || c>max) {//一个错误
max = c;
}
if (mid == -1 || i + c > right) {
right = i + c;
mid = i;
}
}
delete[]newstr;
delete[]count;
return max;
}
void cc(char*p,int n) {
for (int i = 0; i < n; ++i) {
cout << p[i] << endl;
}
}
bool isPalindrome(string s) {
transform(s.begin(), s.end(), s.begin(), ::tolower);
auto left = s.begin(), right = prev(s.end());
while (left < right) {
if (!::isalnum(*left)) ++left;
else if (!::isalnum(*right)) --right;
else if (*left != *right) return false;
else { left++, right--; }
}
return true;
}