Posted onEdited onInLeetCodeDisqus: Symbols count in article: 3.2kReading time ≈3 mins.
manacher’s algorithm可以O(n)但是不会 O(n2)
1 2 3 4 5 6 7 8 9 10 11 12 13 14
classSolution: deflongestPalindrome(self, s: str) -> str: deffind(l, r): while0 <= l and r < len(s) and s[l] == s[r]: l -= 1 r += 1 return l + 1, r - 1 ll, rr = 0, 0 for i inrange(len(s)): l, r = find(i, i) if r - l > rr - ll: ll, rr = l, r l, r = find(i, i + 1) if r - l > rr - ll: ll, rr = l, r return s[ll:rr + 1]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
classSolution: deflongestPalindrome(self, s: str) -> str: ll, rr = 0, 0 for i inrange(len(s)): l, r = self.find(s, i, i) if r - l > rr - ll: ll, rr = l, r l, r = self.find(s, i, i + 1) if r - l > rr - ll: ll, rr = l, r return s[ll:rr + 1]
deffind(self, s, l, r): while0 <= l and r < len(s) and s[l] == s[r]: l -= 1 r += 1 return l + 1, r - 1
classSolution: deflongestPalindrome(self, s: str) -> str: s = '#' + '#'.join(list(s)) + '#' n = len(s) ll, rr = n, n for i inrange(1, n): l, r = i - 1, i + 1 while0 <= l and r < n and s[l] == s[r]: l -= 1 r += 1 if r - l > rr - ll: ll, rr = l + 1, r - 1 return s[ll + 1 : rr : 2]
classSolution { public: stringlongestPalindrome(string s){ string str = "#"; for (char c : s) { str += c; str += '#'; } int n = str.length(), ll = 0, rr = 0; for (int i = 1; i < n - 1; ++i) { int l = i - 1, r = i + 1; while (0 <= l && r < n && str[l] == str[r]) { --l; ++r; } ++l; --r; if (r - l > rr - ll) { ll = l; rr = r; } } string res; for (int i = ll + 1; i <= rr; i += 2) { res += str[i]; } return res; } };
classSolution { public: stringlongestPalindrome(string s){ string str = split(s); int n = str.length(); int left = 0, right = 0; for (int i = 1; i < n - 1; ++i) { int l = i, r = i; while (str[l] == str[r] && l >= 0 && r < n) { --l; ++r; } ++l; --r; if (r - l > right - left) { left = l; right = r; } } return reconstruct(str, left, right); }
classSolution { public: stringlongestPalindrome(string s){ int n = s.length(), b = 0; m.resize(n, vector<int>(n, -1)); int mx = f(s, 0, n - 1); for (int l = 0, r = l + mx - 1; 0 <= r && r < n; ++l, ++r) { if (m[l][r] == mx) return s.substr(l, mx); } return""; }
intf(conststring &s, int l, int r){ if (l > r) return0; if (m[l][r] > 0) return m[l][r]; if (l == r) return m[l][r] = 1; m[l][r] = max(f(s, l, r - 1), f(s, l + 1, r)); if (s[l] == s[r]) { int t = f(s, l + 1, r - 1); if (l + t + 1 == r) { m[l][r] = max(m[l][r], r + 1 - l); } } return m[l][r]; }