5.最长回文子串

参考https://leetcode-cn.com/problems/longest-palindromic-substring/solution/zui-chang-hui-wen-zi-chuan-by-leetcode-solution/  Leetcode官方题解

讲得真心好啊

我就不赘述了,c++

 

1.暴力法

时间复杂度O(N^3) 空间复杂度O(N 1)

只能通过43个样例,第44个超时

class Solution {
public:
    string longestPalindrome(string s) {
        /**
        暴力法  时间复杂度O(n^3) 空间复杂度O(n1)
        **/
        int len=s.size();
        if(len<2)
            return s;
        int maxn=1,first=0;
        for(int i=0;i<len-1;++i)
        {
            for(int j=i+1;j<len;++j)
            {
                if(j-i+1>maxn&&Find(s,i,j))
                {
                    maxn=j-i+1;
                    first=i;
                }
            }
        }
        return s.substr(first,maxn);

    }
    static bool Find(string s,int first,int second)
    {
        while(first<second)
        {
            if(s[first]!=s[second])
                return false;
            first++;
            second--;
        }
        return true;
    }

};

2.动态规划

class Solution {
public:
    string longestPalindrome(string s) {
        int len=s.size();
        if(len<2)
            return s;
        int first=0;
        int maxn=1;
        vector<vector<int> >dp(len,vector<int>(len));
        for(int i=0;i<len;++i)
        {
            dp[i][i]=1;
            if(i<len-1&&s[i]==s[i+1])
            {
                dp[i][i+1]=1;
                maxn=2;
                first=i;
            }
        }

        for(int l=3;l<=len;++l)
        {
            for(int i=0;i+l-1<len;++i)
            {
                int j=i+l-1;
                if(s[i]==s[j]&&dp[i+1][j-1]==1)
                {
                    dp[i][j]=1;
                    first=i;
                    maxn=l;
                }
            }
        }
        return s.substr(first,maxn);
    }

};

 

posted @ 2020-05-22 11:06  caishunzhe  阅读(116)  评论(0编辑  收藏  举报