首页 > 代码库 > 5. Longest Palindromic Substring

5. Longest Palindromic Substring

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

==

class Solution {public:    string longestPalindrome(string s) {        /**bool dp[i][j]代表s[i-j]是否回文        dp[i][j] = true         ;i==j                 = s[i]==s[j]   ;j=i+1                 = (s[i]==s[j])&& dp[i+1][j-1]; j>i+1        要记住,dp[i][j]表示的i-j之间的字符串是不是回文,        当i==j时,dp[i][i]当然是回文        当j=i+1时,dp[i][j],要看字符串s[i]和s[j]之间是不是相同的?        当j>i+1时,dp[i][j]的判定情况,s[i]s[j]和dp[i+1][j-1]共同决定的;        怎么开始的?        外层循环j控制,        内存循环i判断当前能到达的位置是否是回文;        */        int n = s.size();        bool dp[n][n];        fill_n(&dp[0][0],n*n,false);///初始化        int max_len = 1;        int start = 0;        for(int j = 0;j<s.size();j++){            for(int i = 0;i<=j;i++){                if(i==j) dp[i][j] = true;                else if(j==(i+1)) dp[i][j] = s[i]==s[j]?true:false;                else if(j>(i+1)) dp[i][j] = s[i]==s[j]&&dp[i+1][j-1];                if(dp[i][j]&&max_len < (j-i+1)){                    max_len = j-i+1;                    start = i;                }            }///for        }        return s.substr(start,max_len);    }};

 

5. Longest Palindromic Substring