您的位置:首页 > 其它

LeetCode 5 最大回文子串

2015-09-14 15:20 246 查看
最大回文子串问题  暴力法肯定超时  请参考百度上的搜索结果 这里只是简单提一下和心思想

加什么符号%@#&……的不说了随意就好 设置数组其他文章里也有(这里为len[])

这里说三个主要变量

例子 12321**************(后面的元素暂时没有遍历到)

max 当前已经搜索到的最大字串的半径(max=3)

pos 最大字串对称点(2,0开始)

I   当前遍历到的元素序号

核心思想为三个判断

1. I<max且max-I>len[2*pos-i](找到与i关于pos对称位置的元素)。这里说的是根据回文字串特性,如果当前的元素s[I]在一个更大的回文字串中,且距离边界的距离小雨i关于pos对称点的距离,说明以s[I]为中心的回文字串完全包括在这个更大的字串中,且有一个对称的“兄弟”。这时候len[i]=len[2-pos-i]

2. I<max且max-I<=len[2*pos-i] 这情况说明以I为中心的回文串可能会超过最大边界max,这时候就需要进行中心扩展匹配, 算法大家都会。

3. I>max 没说的 这时候已经遍历到未知区域了 只能去匹配。

c# code

public class Solution
{
    public string LongestPalindrome(string str)
    {
        string s = Init(str);
        //Console.WriteLine(s);
        int[] len = new int[s.Length];
        int max = 0, pos = 0;
        for (int i = 0; i < len.Length; i++)
        {
            if (i < max)
            {
                if (len[2 * pos - i] < max - i)
                {
                    len[i] = len[2 * pos - i];
                }
                else
                {
                    int a = Extend(i, s);
                    if (a > max)
                    {
                        max = a;
                        pos = i;
                    }
                }
            }
            else
            {
                int a = Extend(i, s);
                if (a > max)
                {
                    max = a;
                    pos = i;
                }
            }
        }
        string result = "";
        for (int i = pos - max + 1; i < pos + max - 1; i++)
        {
            result += s[i];
        }
        return result.Replace("#","");
    }
    static string Init(string s)
    {
        char[] str = new char[2 * s.Length + 1];
        for (int i = 0; i < s.Length; i++)
        {
            str[i * 2 + 1] = s[i];
            str[2 * i] = '#';
            str[str.Length - 1] = '#';
        }
        return new string(str);
    }
    static int Extend(int i,string s)
    {
        int a = 0;
        while (i - a >= 0 && i + a < s.Length && s[i + a] == s[i - a])
        {
            a++;
        }
        return a;
    }
}


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息