5. longest palindromic substring

题目描述

给一个字符串,求该字符串的最长回文字串。

题目分析

遍历该字符串内的所有字符,以该字符为中心的奇回文串和偶回文串,然后找出最长的串。

代码


struct Key {
    int left;
    int right;
    int length;
};

class Solution {
public:
    std::string longestPalindrome(std::string s) {
        Key tmp;
        Key result = {-1, -1, -1};
        for (unsigned i = 0; i < s.length(); ++i) {
            tmp = getOdd(s, i);
            if (tmp.length > result.length) {
                result = tmp;
            }
            tmp = getEven(s, i);
            if (tmp.length > result.length) {
                result = tmp;
            }
        }
        char buf[1010];
        int j = 0;
        for (int i = result.left; i <= result.right; ++i) {
            buf[j++] = s[i];
        }
        buf[j] = '