5. Longest Palindromic Substring

来源:互联网 发布:卡尔软件 编辑:程序博客网 时间:2024/05/13 08:42

Discription:

Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.

Example:

Input: "babad"Output: "bab"Note: "aba" is also a valid answer.

Example:

Input: "cbbd"Output: "bb"



Explanation:
we can use dynamic programming to solve this problem
define dp[i][j] as whether substring of s from i to j is palindrome
for each pair i and j (j>=i)
if (i==j) dp[i][j]=true;
else if(s[i]==s[j] && (i>=j-1 || dp[i+1][j-1]==true)) dp[i][j]=true;
else dp[i][j]=false;

so for every substring we can know wether it is palindrom, and get the max one.





Implement code:
C++:

class Solution {
public:
    string longestPalindrome(string s) {
        int l=s.size();
        if(l<2)return s;
        vector<vector<bool> > ans(l, vector<bool>(l, false));
        
        int ai=0, aj=1;
        
        for(int i=l-1;i>=0;--i)
        {
            for(int j=i;j<l;++j)
            {
                if(s[i] == s[j] && (i>=j-1 || ans[i+1][j-1] == true))ans[i][j]=true;
                
                if(ans[i][j] == true && j-i+1>aj)
                {
                    ai = i;
                    aj = j-i+1;
                }
            }
        }
        
        return s.substr(ai, aj);
        
    }
};


Java:

class Solution {
public:
    string longestPalindrome(string s) {
        int l=s.size();
        if(l<2)return s;
        vector<vector<bool> > ans(l, vector<bool>(l, false));
        
        int ai=0, aj=1;
        
        for(int i=l-1;i>=0;--i)
        {
            for(int j=i;j<l;++j)
            {
                if(s[i] == s[j] && (i>=j-1 || ans[i+1][j-1] == true))ans[i][j]=true;
                
                if(ans[i][j] == true && j-i+1>aj)
                {
                    ai = i;
                    aj = j-i+1;
                }
            }
        }
        
        return s.substr(ai, aj);
        
    }
};

原创粉丝点击