1、待解決
/*給定一個字串s,你可以從中刪除一些字元,使得剩下的串是一個迴文串,*如何刪除才能使得迴文串最長呢。 *輸出需要刪除的字元個數*輸入描述:輸入資料有多組,每組包含一個字串s,且保證,1<=s.length<=1000.*輸出描述:對於每組資料輸出一個整數,代表最少需要刪除的字元個數。*輸入例子:* abcda * google*輸出例子:* 2* 2*/#include <iostream>#include <cstring>using namespace std;#define MAX 1000char* Del_ch (char* str, int len, int n);int Num_ch (char* str, int len) { char Nor_str[MAX]; char Rev_str[MAX]; for (int i = 0, j = len-1; i < len; i++, j--) { Nor_str[i] = str[i]; Rev_str[i] = str[j]; } //cout<<Nor_str<<endl; //cout<<Rev_str<<endl; int max = 0; for (int i = 0,j = 0; i < len; i++,j++) { for (; j < len; j++) { if (Nor_str[i] == Rev_str[j]) { max++; //cout<<j<<endl; break; } } //cout<<max<<endl; } return len - max; //cout<<max<<endl; //cout<<Nor_str<<endl; //cout<<Rev_str<<endl;}//刪除字串裡的某個元素,形成一個新的串char* Del_ch (char* str, int len, int n) { char* temp = str; for (int i = n; i < len-1; i++) { str[i] = str [i+1]; } str[len-1] = '\0'; return temp;} int main (void) { char str[] = "google"; cout<<str<<endl; int len = strlen(str); cout<<Num_ch(str,len)<<endl; //Del_str(str, len, 5); //cout<<str<<endl; return 0;}
優解
#include<iostream>#include<string>#include<algorithm>using namespace std;const int MAX = 1001;int MaxLen[MAX][MAX]; //最長公用子序列,動態規劃求法int maxLen(string s1, string s2){ int length1 = s1.size(); int length2 = s2.size(); for (int i = 0; i < length1; ++i) MaxLen[i][0] = 0; for (int i = 0; i < length2; ++i) MaxLen[0][i] = 0; for (int i = 1; i <= length1; ++i) { for (int j = 1; j <= length2; ++j) { if (s1[i-1] == s2[j-1]){ MaxLen[i][j] = MaxLen[i-1][j - 1] + 1; } else { MaxLen[i][j] = max(MaxLen[i - 1][j], MaxLen[i][j - 1]); } } } return MaxLen[length1][length2];}int main(){ string s; while (cin >> s){ int length = s.size(); if (length == 1){ cout << 1 << endl; continue; } //利用迴文串的特點 string s2 = s; reverse(s2.begin(),s2.end()); int max_length = maxLen(s, s2); cout << length - max_length << endl; } return 0;}