删除最短偶数长度回文子串
1. 判断是不是回文串:
bool isPalindrome(const string& s) {
int left = 0, right = s.length() - 1;
while (left < right) {
if (s[left] != s[right])
return false;
left ++;
right --;
}
return true;
}
2. 动态
string removeShortestPalindrome(string s) {
if (s.empty()) return s;
int n = s.length();
vector<vector<bool> > dp(n, vector<bool>(n, false));
// 初始化长度为1和2的回文串
for (int i = 0; i < n; i++) {
dp[i][i] = true;
if (i < n - 1 && s[i] == s[i + 1])
dp[i][i + 1] = true;
}
// 动态规划填充dp表
for (int len = 3; len <= n; len++) {
for (int i = 0; i + len - 1 < n; i++) {
int j = i + len - 1;
if (s[i] == s[j] && dp[i + 1][j - 1])
dp[i][j] = true;
}
}
// 找到最短回文子串的起始位置和长度
int start = 0, min_len = n;
for (int i = 0; i < n; i++) {
for (int j = i; j < n; j++) {
if (dp[i][j] && (j - i + 1) % 2 == 0 && (j - i + 1) < min_len) {
start = i;
min_len = j - i + 1;
}
}
}
// 删除最短回文子串
if (min_len == n) return ""; // 整个字符串都是回文串
return s.substr(0, start) + s.substr(start + min_len);
}