5. Longest Palindromic Substring

來源:互聯網
上載者:User
<pre style="box-sizing: border-box; overflow: auto; font-family: Menlo, Monaco, Consolas, 'Courier New', monospace; font-size: 13px; padding: 9.5px; margin-top: 0px; margin-bottom: 10px; line-height: 1.42857; color: rgb(51, 51, 51); word-break: break-all; word-wrap: break-word; border: 1px solid rgb(204, 204, 204); border-top-left-radius: 4px; border-top-right-radius: 4px; border-bottom-right-radius: 4px; border-bottom-left-radius: 4px; font-variant-ligatures: normal; font-variant-position: normal; font-variant-numeric: normal; font-variant-alternates: normal; font-variant-east-asian: normal; widows: 1; background-color: rgb(245, 245, 245);">還有一種遍曆中心的方法時間複雜度也為n方,還有一種為n的方法
class Solution {public:    string longestPalindrome(string s) {        int length = s.length();        if(length == 0 || length == 1) return s;        vector<vector<int>> dp(length+5,vector<int>(length+5,0));        dp[length-1][length-1]=1;        int start = 0,max = 0;        for(int i=0;i<length-1;i++){            dp[i][i]=1;            if(s[i]==s[i+1]) {                dp[i][i+1]=1;                start = i;                max = 2;            }        }        for(int j=2;j<length;j++){            for(int i=0;i<=j;i++){                if(s[i]==s[j]&&dp[i+1][j-1]){                    if(j-i+1>max){                        start = i;                        max = j-i+1;                    }                    dp[i][j]=1;                }            }        }        for(int i=0;i<length;i++){            for(int j=0;j<length;j++)            cout<<dp[i][j];            cout<<endl;        }        return s.substr(start,max);    }};

"abaas"

10100
01000
00110
00010
00001

聯繫我們

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