LeetCode #5 Longest Palindromic Substring C# Solution

LeetCode #5 Problem
Given a string S, find the longest palindromic substring in S. You may assume that the maximum length of S is 1000, and there exists one unique longest palindromic substring.

这题是一个求最长回文子串的题目,题目的数据量不大,其实应该是可以用后缀数组做的,但是查了资料之后发现了一个神奇的算法:Manacher算法,这个算法可以在O(n)的时间复杂度下求出最长回文子串。这个算法的精妙之处就在于在字符串首尾和每两个字符之间添加一个特殊变量以规避奇数和偶数长度字符串带来的麻烦,同时引入了md和id这两个辅助变量用于在O(n)的时间内求出辅助数组P[i],也就是以每个字符为中心的回文串长度。
关于求P[i]数组,我参考了 http://blog.csdn.net/ggggiqnypgjg/article/details/6645824 的求法,原博客图文并茂相当清楚就不在赘述了。

C# Code
    public class Solution
    {
        public string stringEncode(string str)
        {
            string s = "";
            s += "$#";
            for (int i = 0; i < str.Length; i++)
            {
                s += str[i];
                s += "#";
            }
            return s;
        }
        public string LongestPalindrome(string str)
        {
            string s = stringEncode(str);
            int[] p = new int[s.Length + 1];
            int mx = 0, id = 0;
            for (int i = 1; i <= s.Length; i++)
            {
                if (mx > i)
                    p[i] = (p[2 * id - i] < (mx - i) ? p[2 * id - i] : (mx - i));
                else
                    p[i] = 1;
                while ((i + p[i] <= s.Length - 1) && (i + p[i] >= 0) && s[i - p[i]] == s[i + p[i]])
                    p[i]++;
                if (i + p[i] > mx)
                {
                    mx = i + p[i];
                    id = i;
                }
            }
            int max = 0, j = 0;
            for (int i = 1; i < s.Length; i++)
                if (p[i] > max)
                {
                    j = i;
                    max = p[i];
                }
            int start = j - max + 1, end = j + max - 1;
            string ans = "";
            for (int i = start; i <= end; i++)
            {
                if (s[i] != '#')
                {
                    ans += s[i];
                }
            }
            return ans;
        }
    }

这里写图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值