[LeetCode] 005. Longest Palindromic Substring (Medium) (C++/Java/Python),leetcodepython
索引:[LeetCode] Leetcode 題解索引 (C++/Java/Python/Sql)
Github: https://github.com/illuz/leetcode
005.Longest_Palindromic_Substring (Medium)
連結:
題目:https://oj.leetcode.com/problems/Longest-Palindromic-Substring/
代碼(github):https://github.com/illuz/leetcode
題意:
求一個字串中的最長迴文子串。
分析:
迴文的解法有不少:
本題要用第三種演算法。
需要注意的是, Python 和 Java 的字串和 C++ 的不一樣,沒有 \0 結尾,用’Manacher’s ALGORITHM’的時候是不一樣的。
代碼:
C++:
class Solution {public:string longestPalindrome(string s) {int p[N<<1];string t = "$";for (char ch : s) {t += '#';t += ch;}t += '#';// t為處理過的字串,p為記錄長度的數組 memset(p, 0, sizeof(p)); // mx為已判斷迴文串最右邊位置,id為中間位置,mmax記錄p數組中最大值 int mx = 0, id = 0, mmax = 0; int len = t.length();int right = 0;for (int i = 1; i < len; i++) { p[i] = mx > i ? min(p[2 * id - i], mx - i) : 1; while (t[i + p[i]] == t[i - p[i]]) p[i]++; if (i + p[i] > mx) { mx = i + p[i]; id = i; } if (mmax < p[i]) {mmax = p[i]; right = i;}} // 最長為mmax - 1 return s.substr(right/2 - mmax/2, mmax-1);}};
Java:
public class Solution { public String longestPalindrome(String s) { int[] p = new int[2048]; StringBuilder t = new StringBuilder("$"); for (int i = 0; i < s.length(); ++i) { t.append('#'); t.append(s.charAt(i)); } t.append("#_"); // mx為已判斷迴文串最右邊位置,id為中間位置,mmax記錄p數組中最大值 int mx = 0, id = 0, mmax = 0; int right = 0; for (int i = 1; i < t.length() - 1; i++) { p[i] = mx > i ? Math.min(p[2 * id - i], mx - i) : 1; while (t.charAt(i + p[i]) == t.charAt(i - p[i])) p[i]++; if (i + p[i] > mx) { mx = i + p[i]; id = i; } if (mmax < p[i]) { mmax = p[i]; right = i; } } // 最長為mmax - 1 return s.substring(right/2 - mmax/2, right/2 - mmax/2 + mmax-1); }}
Python:
class Solution: # @return a string def longestPalindrome(self, s): t = '$#' + '#'.join(s) + '#_' p = [0] * 4010 mx, id, mmax, right = 0, 0, 0, 0 for i in range(1, len(t) - 1): if mx > i: p[i] = min(p[2 * id - i], mx - i) else: p[i] = 1 while t[i + p[i]] == t[i - p[i]]: p[i] += 1 if i + p[i] > mx: mx = i + p[i] id = i if mmax < p[i]: mmax = p[i] right = i return s[right//2 - mmax//2: right//2 - mmax//2 + mmax - 1]