LeetCode-5-Longest Palindromic Characters

算法描述:

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

Example 1:

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

Example 2:

Input: "cbbd"
Output: "bb"

解题思路:

最长回文子串问题,可以用动态规划问题来解决。

回文的定义如下:

P(i,j) = (P(i+1,j-1) and S_{i}==S_{j})

其中:

P(i,i) = true

P(i,i+1) = (S_{i}==S_{i+1})

string longestPalindrome(string s) {
        vector<vector<bool>> dp(s.size(),vector<bool>(s.size(),false));
        int maxCount = 0;
        int left = 0;
        int right = 0;
        for(int i=0; i < s.size(); i++){
            dp[i][i] = true;
            for(int j=0; j < i;j++){
                dp[j][i] = s[i]==s[j] && (dp[j+1][i-1] ||i-j < 2);
                    
                if(dp[j][i] && maxCount < i-j+1){
                    maxCount = i-j+1;
                    left = j;
                    right = i;
                }
            }
        }
        return s.substr(left,right-left+1);
    }

猜你喜欢

转载自www.cnblogs.com/nobodywang/p/10312821.html