LeetCode-5.Longest Palindromic Substring

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.

使用双指针

public class Solution 
{
    public string LongestPalindrome(string s)
    {
       int n = s.Length;
            if (n < 2)
                return s;
            string res = Fun(s,1, "");
            if (n < 3)
                return res;
            return Fun(s,2, res);
    }
    
    private string Fun(string s,int offset,string res)
    {
        int tmp,p1 =0, p2 = offset;
        while (p2 < s.Length)
        {
            if (s[p1] == s[p2])
            {
                tmp = p1 + 1;
                while (p1 >= 0 && p2 < s.Length && s[p1] == s[p2])
                {
                    p1--;
                    p2++;
                }
                if (p2 - p1 - 1 > res.Length)
                {
                    res = s.Substring(p1 + 1, p2 - p1 - 1);
                }
                p1 = tmp;
                p2 = p1 + offset;
            }
            else
            {
                p1++;
                p2++;
            }
        }
        return res;
    }
}


动态规划(并不能提高算法效率)

public string LongestPalindrome(string s)
        {
            int n = s.Length;
            if (n < 2)
                return s;
            string res = "";
            bool[,] b = new bool[n,n];
            int max = 0;
            for (int i= n-1; i >=0; i--)
            {
                for (int j = i; j < n; j++)
                {
                    if (s[i] == s[j] && (j - i < 3 || b[i+1,j - 1]))
                    {
                        b[i,j] = true;
                        if (j - i + 1 > max)
                        {
                            max = j - i + 1;
                            res = s.Substring(i, max);
                        }
                    }
                }
            }
            return res; 
        }
参考: http://blog.csdn.net/linhuanmars/article/details/20888595

你可能感兴趣的:(LeetCode)