Longest Palindromic Substring[leetcode] O(n^2)的DP和O(n)的演算法,longestsubstring

來源:互聯網
上載者:User

Longest Palindromic Substring[leetcode] O(n^2)的DP和O(n)的演算法,longestsubstring

實現了兩種方法,一種是DP,用迴圈做的,遞迴的話更簡單。

string longestPalindrome(string s) {        int n = s.size();        bool dp[1001][1001];        int maxl = 1;        int maxs = 0;        for (int i = n - 1; i >= 0; i--)        {            dp[i][i] = true;            for (int j = i + 1; j < n; j++)            {                if (s[i] == s[j] && (j == i + 1 || dp[i + 1][j - 1]))                {                    dp[i][j] = true;                    if (maxl < (j - i + 1))                    {                        maxl = (j - i + 1);                        maxs = i;                    }                }                else                    dp[i][j] = false;            }        }        return s.substr(maxs, maxl);    }


另外一種是比較有名的O(n)的方法

string longestPalindrome(string s) {        int n = s.size();        int newn = n * 2 + 1;        int p[2000];        char * news = new char[newn];        for (int i = 0; i < n; i++)        {            news[2 * i] = '*';            news[2 * i + 1] = s[i];        }        news[2 * n] = '*';        //s:abac        //news:*a*b*a*c*         //P:   121412121        int mx = 0;        int mi = 0;        int maxLen = 0;        int maxIndex = 0;        for (int i = 0; i < newn; i++)        {            if (mx > i)                p[i] = min(p[2 * mi - i], mx - i);            else                p[i] = 1;            for (;i - p[i] >= 0 && i + p[i] < newn && news[i + p[i]] == news[i - p[i]];p[i]++);            if (p[i] + i > mx)            {                mx = p[i] + i;                mi = i;            }            if (maxLen < p[i] - 1)            {                maxLen = p[i] - 1;                maxIndex = i;            }        }        string returnVal = s.substr((maxIndex - maxLen) / 2, maxLen);        delete [] news;                return returnVal;    }







聯繫我們

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