最长回文字串 (LEETCODE: Longest Palindromic Substring)

根据回文的特征,从字符串中某个位置(或某两个位置)为中心,向两边开始分析。直至找到最长的回文串。

(注意考虑回文可能形如 aba,也可能形如abba,即可能为奇数,也可能为偶数)
  

string longestPalindrome(string s)
{
//中心扩展法
    int maxlen;
    int prev;
    int next;
    string result;
    maxlen = 0;

    //回文串为奇数时
    for (int i = 0; i < s.size(); i++)
    {
        prev = i;
        next = i;
        while (true)
        {
            prev = prev - 1;
            next = next + 1;
            if (prev < 0 || next > s.size() - 1)
            {
                if ((next - 1) - (prev + 1) + 1 > maxlen)
                {
                    maxlen = (next - 1) - (prev + 1) + 1;
                    result.assign(s, prev + 1, maxlen);
                }
                break;
            }
            if (s[prev] != s[next])
            {
                if ((next - 1) - (prev + 1) + 1 > maxlen)
                {
                    maxlen = (next - 1) - (prev + 1) + 1;
                    result.assign(s, prev + 1, maxlen);
                }
                break;
            }
        }
    }

        //回文串为偶数时
    for (int i = 0; i < s.size(); i++)
    {
        prev = i;
        next = i+1;
        if (prev >= 0 && next <= s.size() - 1 && s[prev] == s[next])
        {
            while (true)
            {
                prev = prev - 1;
                next = next + 1;
                if (prev < 0 || next > s.size() - 1)
                {
                    if ((next - 1) - (prev + 1) + 1 > maxlen)
                    {
                        maxlen = (next - 1) - (prev + 1) + 1;
                        result.assign(s, prev + 1, maxlen);
                    }
                    break;
                    }
                if (s[prev] != s[next])
                {
                    if ((next - 1) - (prev + 1) + 1 > maxlen)
                    {
                        maxlen = (next - 1) - (prev + 1) + 1;
                        result.assign(s, prev + 1, maxlen);
                    }
                    break;
                }
            }
        }
    }
    return result;
}

在网上还看到了动态规划的解法,本人动态性规划一直没有很透彻的了解,所以这里没选择这种方法解决本题

你可能感兴趣的:(leetcode刷题,c++)