Leetcode--Longest Palindromic Substring

5. Longest Palindromic Substring

class Solution {
public:
    string longestPalindrome(string s) {
        int n = s.size();
        bool f[n][n];
        fill_n(&f[0][0], n * n, false);
        //用vector会超时
        //vector> f(n,vector(n,false));
        int max_len = 1,start_index = 0;
        for (int i = 0; i < n; ++i) {
            f[i][i] = true;
            for (int j = 0; j < i; ++j) { //[j,i]
//                if (j == i - 1) f[j][i] = s[j] == s[i];
//                else f[j][i] = s[j] == s[i] && f[j+1][i-1];
                f[j][i] = (s[j] == s[i] && (i - j < 2 || f[j+1][i-1]));
                if(f[j][i] && max_len < (i - j + 1) ) {max_len = i - j + 1;start_index = j;}
            }
        }
        return s.substr(start_index,max_len);
    }
};

你可能感兴趣的:(Leetcode--Longest Palindromic Substring)