時間限制:1秒
空間限制:32768K
給定一個字符串s,你可以從中刪除一些字符,使得剩下的串是一個迴文串。如何刪除才能使得迴文串最長呢?
輸出需要刪除的字符個數。
輸入描述:
輸入數據有多組,每組包含一個字符串s,且保證:1<=s.length<=1000.
輸出描述:
對於每組數據,輸出一個整數,代表最少需要刪除的字符個數。
輸入例子1:
abcda google
輸出例子1:
2 2
dp。
輸入未知個數的string可以用while(cin >> s)~
#include<stdio.h>
#include<iostream>
#include<string>
#include<algorithm>
#include<sstream>
using namespace std;
const int maxn = 1005;
int dp[maxn][maxn];
int main(){
string s;
while(cin >> s){
fill(dp[0], dp[0]+maxn*maxn, 0);
int len = s.length();
for(int i = 0; i < len; i++){
dp[i][i] = 1;
if(i!=0){
if(s[i] == s[i-1])
dp[i-1][i] = 2;
else
dp[i-1][i] = 1;
}
}
for(int i = 3; i <= len; i++){
for(int st = 0; st+i-1<len; st++){
int ed = st+i-1;
if(s[st] == s[ed]){
dp[st][ed] = max(dp[st+1][ed-1]+2, max(dp[st+1][ed], dp[st][ed-1]));
}
else{
dp[st][ed] = max(dp[st+1][ed-1], max(dp[st+1][ed], dp[st][ed-1]));
}
}
}
cout << len-dp[0][len-1] << endl;
}
return 0;
}