From 7f57ece26f480e29933a3054e9b80ebd79007875 Mon Sep 17 00:00:00 2001 From: uwivbn Date: Mon, 2 Sep 2019 16:17:21 +0800 Subject: [PATCH] =?UTF-8?q?=E5=9B=9E=E6=96=87=E4=B8=B2=E7=9A=84=E9=A9=AC?= =?UTF-8?q?=E6=8B=89=E8=BD=A6=E7=AE=97=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../file_code3.py" | 46 +++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 "5. \346\234\200\351\225\277\345\233\236\346\226\207\345\255\220\344\270\262/file_code3.py" diff --git "a/5. \346\234\200\351\225\277\345\233\236\346\226\207\345\255\220\344\270\262/file_code3.py" "b/5. \346\234\200\351\225\277\345\233\236\346\226\207\345\255\220\344\270\262/file_code3.py" new file mode 100644 index 0000000..aa0c3b5 --- /dev/null +++ "b/5. \346\234\200\351\225\277\345\233\236\346\226\207\345\255\220\344\270\262/file_code3.py" @@ -0,0 +1,46 @@ +class Solution: + # 马拉车算法 + def longestPalindrome(self, s: str) -> str: + T = preprocess(s) + n = len(T) + C, R = 0, 0 + P = [0] * n + + for i in range(1, n-1): + i_mirror = 2 * C - i + P[i] = min(R-i, P[i_mirror]) if R > i else 0 + + while T[i-1-P[i]] == T[i+1+P[i]]: + P[i] += 1 + + if i + P[i] > R: + C = i + R = P[i] + i + + maxlen = 0 + center_index = 0 + for i in range(1, n-1): + if P[i] > maxlen: + maxlen = P[i] + center_index = i + + start_index = (center_index - maxlen) // 2 + return s[start_index: maxlen + start_index] + + +def preprocess(s: str): + temp_str = '' + for i in s: + temp_str += '#' + i + + temp_str = '^' + temp_str + '#$' + return temp_str + +if __name__ == "__main__": + solution = Solution() + # string = 'cbbd' + string = 'babad' + + result = solution.longestPalindrome(string) + + print(result)