[LeetCode] 005. Longest Palindromic Substring (Medium) (C++/Java/Python)

索引:[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

题意

求一个字符串中的最长回文子串。

分析

回文的解法有不少:

  1. 暴力搜索 O(n^3)
  2. 动态规划 O(n^2), dp[i][j] = dp[i + 1][j - 1] (if s[i] == s[j])
  3. Manacher’s ALGORITHM可达到 O(n) 时间。

本题要用第三种算法。

需要注意的是, 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]
时间: 2024-12-25 05:47:09

[LeetCode] 005. Longest Palindromic Substring (Medium) (C++/Java/Python)的相关文章

Java for LeetCode 005 Longest Palindromic Substring

Given a string S, find the longest palindromic substring in S. You may assume that the maximum length of S is 1000, and there exists one unique longest palindromic substring. 解题思路一: 暴力枚举 共N^2量级个子串(从下标零开始),每次检查需一个for循环,等于是3重for循环,时间复杂度O(n^3) 解题思路二: 动态

LeetCode 005 Longest Palindromic Substring - Java

Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000. Example: Input: "babad" Output: "bab" Note: "aba" is also a valid answer. Example: Input: "cbbd" Ou

LeetCode 5. Longest Palindromic Substring(medium难度)

Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000. Example: Input: "babad" Output: "bab" Note: "aba" is also a valid answer. Example: Input: "cbbd" Ou

【LeetCode】005 Longest Palindromic Substring

题目:LeetCode 005 Longest Palindromic Substring Given a string S, find the longest palindromic substring in S. You may assume that the maximum length of S is 1000, and there exists one unique longest palindromic substring. 题意:字符串S,找到S中的最长回文子串.假定S最长为100

LeetCode #5 Longest Palindromic Substring (M)

[Problem] Given a string S, find the longest palindromic substring in S. You may assume that the maximum length of S is 1000, and there exists one unique longest palindromic substring. [Analysis] 这题的思路有很多种,网上也有各种讨论.这里我采用的是个人觉得比较好理解的一种利用Dynamic Progra

LeetCode(4) || Longest Palindromic Substring 与 Manacher 线性算法

LeetCode(4) || Longest Palindromic Substring 与 Manacher 线性算法 题记 本文是LeetCode题库的第五题,没想到做这些题的速度会这么慢,工作之余全部耗在这上面了,只怪自己基础差.本文主要介绍使用Manacher线性算法来求解字符串的最长回文子字符串. 题目 Given a string S, find the longest palindromic substring in S. You may assume that the maxim

LeetCode:Longest Palindromic Substring

Longest Palindromic Substring Given a string S, find the longest palindromic substring in S. You may assume that the maximum length of S is 1000, and there exists one unique longest palindromic substring. 动态规划解法 T(n) = O(n^2)  ,S(n) = O(n^2); Solutio

[LeetCode] 5. Longest Palindromic Substring 最长回文子串

Given a string S, find the longest palindromic substring in S. You may assume that the maximum length of S is 1000, and there exists one unique longest palindromic substring. 最长回文子串Longest palindromic substring, 最长回文子串或最长对称因子问题是在一个字符串中查找一个最长连续子串,这个子串

LeetCode-Algorithms #005 Longest Palindromic Substring, Database #179 Consecutive Numbers

LeetCode-Algorithms #005 Longest Palindromic Substring 英语学习时间palindromic: [医] 复发的, 再发的 在数学和计算机上,就指回文 这道题目就是找出给定字符串中最长的回文子串, 可以假定原字符串的长度不超过1000 直接遍历来做肯定是不难, 但也可以想见一定是慢得可以. 那么我的另一个想法是, 从原串中的每一个字符, 或每两个字符中间的空隙开始, 向左右两边判断是否为回文串, 最后找出最长的 1 class Solution