[Leetcode] Longest Palindromic Substring

来源:互联网 发布:conoha windows 编辑:程序博客网 时间:2024/06/16 12:46

Given a string S, find the longest palindromic substring in S. You may assume that the maximum length ofS is 1000, and there exists one unique longest palindromic substring.

class Solution {public:    /*algorithm        dp(i,j) is palindrome        dp(i-1,j+1) = 1 if dp(i,j) && s[i-1]==s[j+1]    */    string longestPalindrome(string s) {            int n = s.size();            int dp[1000][1000]={{0}};//if use vector<vector<int>>,it will memmory limited exceeded            int maxLen=1,x=0;            for(int i = n-1;i >=0;i--){                dp[i][i] = 1;                for(int j = i+1;j < n;j++){                    if(s[i]==s[j]&&(j==i+1||dp[i+1][j-1])){                        dp[i][j] = 1;                        if(j-i+1 > maxLen){                            maxLen = j-i+1;                            x = i;                        }                    }                }            }            return s.substr(x,maxLen);    }};


0 0
原创粉丝点击