Leetcode 5——最长回文子串

先附上代码:

class Solution {
public:
    string longestPalindrome(string s) {
    int count = s.size();
    int max = 0;
    string result;
    int j;
    int curlen;
    
    for (int i = 0; i < count; ++i)
    {
        // 如果i为奇数对称
        for (j = 0; (i-j>=0) && (i+j<count); j++)
        {
            if (s[i-j] != s[i+j])
            {
                break;
            }

            curlen = 2 * j + 1;
            if (curlen > max)
            {
                max = curlen;
                result = string(s, i-j, max);
            }    
        }

        // 如果i为偶数对称
        j = 0;
        for(j = 0; (i-j>=0) && (i+j+1 < count); ++j)
        {
            if (s[i-j] != s[i+j+1])
            {
                break;
            }
            curlen = 2*j + 2;
            if (curlen > max)
            {
                max = curlen;
                result = string(s, i-j, max);
            }
        }
    }
    return result;
    }
};

按照书上说的,这种解法叫做中心扩展法,还有一种Manacher算法,有些看不懂,所以,先使用中心扩展法求解最大回文子串。

分类:区分奇数还是偶数;

思路:对每个元素进行遍历,将每个元素作为中心点向两边推进,推进的长度设定step,那么子串长度为2*step+2或2*step+1;始终记录最大长度,并保存相应字符串;

猜你喜欢

转载自www.cnblogs.com/gwzz/p/9200980.html