首页 > 代码库 > LeetCode 5.Longest Palindromic Substring

LeetCode 5.Longest Palindromic Substring

public static string LongestPalindrome(string s)
        {
            string T = preProcess(s);
            int n = T.Length;
            int[] P = new int[n];
            //C是中心位置下标,R是长度
            int C = 0, R = 0;
            //数组P[]中每个元素P[i]中的i为T的下标,P[i]的值为以i为中心的回文字的最大长度
            for (int i = 1; i < n - 1; i++)
            {
                //如果i是回文字中心的话,那么i_mirror就是回文字的起始位置
                int i_mirror = C - (i - C); 
                P[i] = (R > i) ? Math.Min(R - i, P[i_mirror]) : 0;

                // Attempt to expand palindrome centered at i
                //检查以i为中心的回文字的最大长度,并将长度设置为P[i]
                while (T[i + 1 + P[i]] == T[i - 1 - P[i]])
                {
                    //检查条件每次增加P[i]+1,满足条件则将P[i]的值加1
                    P[i]++;
                }

                // If palindrome centered at i expand past R,
                // adjust center based on expanded palindrome.
                if (i + P[i] > R)
                {
                    C = i;
                    R = i + P[i];
                }
            }

            // Find the maximum element in P.
            //P[i]最大值时,i为中间位置,P[i]为长度
            int maxLen = 0;
            int centerIndex = 0;
            for (int i = 1; i < n - 1; i++)
            {
                if (P[i] > maxLen)
                {
                    maxLen = P[i];
                    centerIndex = i;
                }
            }
            return s.Substring((centerIndex - 1 - maxLen) / 2, maxLen);
        }

        // Transform S into T.
        // For example, S = "abba", T = "^#a#b#b#a#$".
        // ^ and $ signs are sentinels appended to each end to avoid bounds checking
        static string preProcess(string s)
        {
            int n = s.Length;
            if (n == 0) return "^$";
            string ret = "^";
            for (int i = 0; i < n; i++)
                ret += "#" + s.Substring(i, 1);

            ret += "#$";
            return ret;
        }

 

LeetCode 5.Longest Palindromic Substring