C++筆試簡單練習——最長迴文字串__C++

來源:互聯網
上載者:User

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;}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.