设d(i)为字符1~i划分为最小回文串的个数(下标从1考虑)
d(i) = min { d(j) +1 | s[j+1~i]是回文串 }
可以先用O(n2)的时间复杂度预处理字符串的每个子串是否为回文串,有如下两种方法:
暴力
实际上以字符串的某个字符为中心,使用双指针向两边扩散,但是要分为三种情况具体讨论
回文串长度为奇数,那么该字符为中位数,初始指针分别为该元素下标的前一个和后一个
回文串长度为偶数,且该字符作为中心线偏左的元素,初始指针分别为该元素下标本身和后一个
回文串长度为偶数,且该字符作为中心线偏右的元素,初始指针分别为该元素下标本身和前一个
bool vis[maxn][maxn];
char s[maxn];
for(int i=1;i<=n;i++){
vis[i][i]=1;
int l=i-1,r=i+1;
while(l>=1 && r<=n && s[l]==s[r]){
vis[l][r]=1;
l--,r++;
}
l=i,r=i+1;
while(l>=1 && r<=n && s[l]==s[r]){
vis[l][r]=1;
l--,r++;
}
l=i-1,r=i;
while(l>=1 && r<=n && s[l]==s[r]){
vis[l][r]=1;
l--,r++;
}
}
dp
设dp(i,j),i<=j代表区间[i,j]的子串为回文串
考虑双重循环,第一层枚举字符串所有字符,第二层枚举它前面的所有字符,那么显然这里存在一个递推关系
当s[i]==s[j]且i-j>1且dp(j+1,i-1)==1时,显然dp(j,i)=1
当s[i]==s[j]且i-j<=1时,dp(j,i)=1
bool dp[maxn][maxn];
char s[maxn];
for(int i=1;i<=n;i++){
dp[i][i]=1;
for(int j=1;j<i;j++)
if(s[i]==s[j]){
if(i-j<=1) dp[j][i]=1;
else if(dp[j+1][i-1])
dp[j][i]=1;
}
}
总的时间复杂度O(n2)
#include <set>
#include <map>
#include <stack>
#include <queue>
#include <math.h>
#include <cstdio>
#include <string>
#include <cstring>
#include <sstream>
#include <iostream>
#include <algorithm>
#include <unordered_map>
using namespace std;
#define lowbit(x) (x&(-x))
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int,int> P;
const double eps=1e-8;
const double pi=acos(-1.0);
const int inf=0x3f3f3f3f;
const ll INF=1e18;
const int Mod=1e9+7;
const int maxn=1005;
bool vis[maxn][maxn];
int d[maxn];
char s[maxn];
int main(){
//freopen("in.txt","r",stdin);
//freopen("out.txt","w",stdout);
//ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);
int t;
scanf("%d",&t);
while(t--){
scanf("%s",s+1);
int n=strlen(s+1);
memset(vis,0,sizeof vis);
for(int i=1;i<=n;i++){
vis[i][i]=1;
for(int j=1;j<i;j++)
if(s[i]==s[j]){
if(i-j<=1){
vis[j][i]=1;
}else if(vis[j+1][i-1]){
vis[j][i]=1;
}
}
}
for(int i=1;i<=n;i++){
d[i]=i;
for(int j=0;j<i;j++){
if(vis[j+1][i]){
d[i]=min(d[j]+1,d[i]);
}
}
}
printf("%d\n",d[n]);
}
return 0;
}