传送门
实现代码
#include<iostream>
#include<cstring>
using namespace std;
const int maxn = 1e3;
const int inf = 0x3f3f3f3f;
bool isPaline[maxn][maxn];
int cnt[maxn];
int count(string str) {
int len = str.length();
memset(isPaline, false, sizeof(isPaline));
memset(cnt, inf, sizeof(cnt));
for (int i = 0; i < len; i++) {
for (int j = i; j >= 0; j--) {
if ( j == i || (str[j] == str[i] && (i == j + 1 || isPaline[j + 1][i - 1]))) {
isPaline[j][i] = true;
if (j == 0) cnt[i] = 1;
else if (cnt[j - 1] + 1 < cnt[i]) cnt[i] = cnt[j - 1] + 1;
}
}
}
return cnt[len - 1];
}
int main() {
int n;
string str;
cin >> n;
while (n--) {
cin >> str;
cout << count(str) << endl;
}
return 0;
}