求字串中的最長迴文子串

來源:互聯網
上載者:User

標籤:os   io   for   art   ar   amp   size   ios   

題目:給定一個字串S,求其中的最長的迴文子串!
思路:採用動態規劃的思想

/*** author :wxg*/ #include<iostream>#include<string>using namespace std;/***動態規劃的思想:字串 S,以及  f(i,j)表示子字串 S[i,j] 是否為迴文,如果是,f(i,j)=true,否則為  false;             ----- true           ,i == jf (i, j) =  ----  S[i] = S[j]    ,j == i + 1            ----- S[i]=S[j]&&f(i+1,j-1)   ,j > i + 1*/int getLongestPalindromic(string str){    int max_len=0,start,end;    const int len=str.size();    bool f[len][len];    int i=0,j=0;    for(i=0;i<len;i++){        for(j=i;j<len;j++){            f[i][j]=false;        }    }    for(i=len-1;i>=0;i--){  //注意 i與j的取值,如果 i=0開始,那麼f(0,4)就會出錯,因為,f(2,3)等中間很多子字串並沒有判斷是否為迴文         for(j=i;j<=len-1;j++){            if(i==j){                f[i][j]=true;            }            else if(j==i+1){                if(str[i]==str[j]) {                    f[i][j]=true;                }            }else if(j>i+1){                if(str[i]==str[j]){                    f[i][j]=f[i+1][j-1];                }            }        }    }    for(i=0;i<len;i++){        for(j=i;j<len;j++){            if(f[i][j]==true){                if(j-i+1>max_len){                    max_len=j-i+1;                    start=i;end=j;                }            }        }    }    cout<<"max_len="<<max_len<<"  start="<<start<<"  end="<<end<<endl;    cout<<str.substr(start,max_len)<<endl;    return max_len;}int main(){    string str="wxxgggxg";    int longest=getLongestPalindromic(str);    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.