UVA 11151 Longest Palindrome (最大迴文串)

來源:互聯網
上載者:User

這裡面讀題一定要精準,首先它說的是從一個string裡面take away一些字元,使得剩下的字元成為一個palindrome,這裡求的是palindrome的最大長度,那麼也就是說刪除最少的字元使得這個string成為一個palindrome,並且可是在原串不連續的。

那麼這個道題和之前做的longest palindrome還有有區別的,之前一定是substring,表示一定是在原串中連續的,及連通的,這個不一定。

那麼如果是palindrome的話,那麼從前往後和從後往前都是一樣的,朋友說求一下本串和逆串的最大公用子序列,沒有錯,就是這樣的,在本串中存在,在逆串中也存在,那麼就說明從前讀和從後讀是一樣的,而LCS就是最大palindrome了!

代碼如下:

//LCS#include <cstdio>#include <string>#include <cstring>#include <iostream>#include <algorithm>using namespace std;int c[1000][1000], T;string s, ss;int main(){    scanf("%d", &T);    getchar();    while ( T-- ) {        getline( cin, s );        if ( s == "" ) {            printf("0\n");            continue;        }        ss.clear();        for ( int i = s.size() -1; i >= 0; ss += s[i], --i );        memset( c, 0, sizeof(c) );        int n = ss.size();        for ( int i = 1; i <= n; ++i )             for ( int j = 1; j <= n; ++j ) {                if ( s[i-1] == ss[j-1] ) c[i][j] = c[i-1][j-1] + 1;                else c[i][j] = max( c[i-1][j], c[i][j-1] );            }        printf("%d\n", c[n][n]);    }}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.