Longest Palindromic Substring

法1(python):利用helper function遍历数组中每一个元素直到找到相对应的最长回文串

时间复杂度O(n^2), 空间复杂度O(n)

class Solution(object):
    def longestPalindrome(self, s):
        """
        :type s: str
        :rtype: str
        """
        res = ""
        for i in range(len(s)):
            tmp = self.helper(s, i, i)
            if len(tmp) > len(res):
                res = tmp
            tmp = self.helper(s, i, i+1)
            if len(tmp) > len(res):
                res = tmp
        return res

    def helper(self, s, l , r):
        while l >= 0 and r < len(s) and s[l] == s[r]:
            l -= 1; r += 1
        return s[l+1:r]

方法2:

dp方法,找到回文规律是,要不然元素个数为2,要不然是真回文,如果是真回文,那它的子集也应该是真回文

时间复杂度:O(n^2), 空间复杂度:O(n^2)

class Solution {
    public String longestPalindrome(String s) {
        int n = s.length(), left = 0, right = 0, res = 0;
        if (n == 0) return s;
        boolean[][] dp = new boolean[n][n];
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < i; j++) {
                dp[j][i] = (s.charAt(i) == s.charAt(j) && ((i - j < 2) || dp[j + 1][i - 1]));
                if (dp[j][i] && (res < i - j + 1)) {
                    res = i - j + 1;
                    left = j;
                    right = i;
                }
            }
            dp[i][i] = true;
           
        }
        return s.substring(left,right + 1);
    }
}

法3:

马拉车算法,有点难,3摸再过吧

posted @ 2018-07-31 16:36  soupsoup88  阅读(89)  评论(0)    收藏  举报