LeetCode "Longest Palindromic Substring" - 1D DP

來源:互聯網
上載者:User

標籤:style   blog   color   io   for   art   ar   div   

2D DP is an intuitive solution of course, but I got an MLE error, so I simplified it into a 1D DP:

class Solution {public:    void goDp(vector<int> &dp, int &maxLen, int &is, int &ie, int startLen, int len, string &s)    {        for(int ilen = startLen; ilen < len; ilen += 2)        for(int i = 0; i < len - ilen; i ++)        {            bool bEq = s[i] == s[i + ilen];            dp[i] = bEq ? (dp[i + 1] > 0 ? dp[i + 1] + 2 : 0) :    0;            if( dp[i] > maxLen)            {                maxLen = dp[i];                is = i; ie = i + ilen;            }        }    }    string longestPalindrome(string s) {        int len = s.length();        if(len == 0) return "";        int maxLen = -1; int is = 0, ie = 0;        //     Init        vector<int> dp; dp.resize(len);                //    Starting from 2        for(int i = 0; i < len - 1; i ++)        {            if(s[i] == s[i + 1]) dp[i] = 2;            else dp[i] = 0;            if( dp[i] > maxLen)            {                maxLen = dp[i];                is = i; ie = i + 1;            }        }                goDp(dp, maxLen, is, ie, 3, len, s);        //    Starting from 1        std::fill(dp.begin(), dp.end(), 1);        goDp(dp, maxLen, is, ie, 2, len, s);        return s.substr(is, ie - is + 1);    }};

Since loop on current length n depends linearly on dp data with length n-1, we can use 1D DP. And there are two cases of odd\even lengthes.

聯繫我們

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