Index: [Leetcode] leetcode key index (C++/JAVA/PYTHON/SQL)
Github:https://github.com/illuz/leetcode
005.longest_palindromic_substring (Medium)
links:
Title: https://oj.leetcode.com/problems/Longest-Palindromic-Substring/
Code (GitHub): Https://github.com/illuz/leetcode
Test Instructions:
The longest palindrome substring in a string.
Analysis:
There are many solutions to palindrome:
- Violent search O (n^3)
- Dynamic planning O (n^2),
dp[i][j] = dp[i + 1][j - 1] (if s[i] == s[j])
- O (n) time can be reached with Manacher ' s algorithm.
The third algorithm is used in this case.
It is important to note that Python and Java strings are not the same as C + +, and do not \0 end with ' manacher ' algorithm '.
Code:
C++:
Class Solution {Public:string Longestpalindrome (string s) {int p[n<<1];string t = "$"; for (char ch:s) {T + = ' # '; t + = ch;} T + = ' # ';//T is a processed string, p is an array of record lengths memset (p, 0, sizeof (p)); MX is the rightmost position of the determined palindrome, ID is the middle position, Mmax records the maximum value in the P array 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;}} The longest is 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 is the rightmost position of the determined palindrome, ID is the middle position, Mmax records the maximum value in the p array 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; }}//Longest is 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]
[Leetcode] 005. Longest palindromic Substring (Medium) (C++/java/python)