[Leetcode] Longest Palindromic Substring

class Solution {
public:
    string longestPalindrome(string s) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        if (s.size() == 0) return "";
        
        int mat[1002][1002];
        int length = s.size();
        mat[0][0] = 0;
        for (int i = 1; i <= s.size(); ++i)
        {
            mat[0][i] = 0;
            mat[i][0] = 0;
        }
        
        
        int maxLength = 0;
        int maxI = -1, maxJ = -1;
        for (int i = 1; i <= length; ++i)
        {
            for (int j = 1; j <= length; ++j)
            {
                if (s[i - 1] == s[length - j])
                {
                    mat[i][j] = mat[i - 1][j - 1] + 1;
                    if (mat[i][j] > maxLength)
                    {
                        maxLength = mat[i][j];
                        maxI = i, maxJ = j;
                    }
                }
                else
                    mat[i][j] = 0;
            }
        }
        
        return s.substr(maxI - maxLength, maxLength);
    }
};

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