LeetCode | 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.

分析

大牛给出了5种解法:

http://leetcode.com/2011/11/longest-palindromic-substring-part-i.html

http://leetcode.com/2011/11/longest-palindromic-substring-part-ii.html

重点是第五种:Manacher,O(n)的时间复杂度,具体分析看大牛的解释,英文看不懂的话,文章里还给了一篇中文的链接

解答

public class LongestPalindromicSubstring {
	public String longestPalindrome(String s) {
		int N = s.length();
		int M = 2 * N + 3;
		char[] c = new char[M];
		c[0] = '$';
		for (int i = 0; i < N; ++i) {
			c[i * 2 + 1] = '#';
			c[i * 2 + 2] = s.charAt(i);
		}
		c[M - 2] = '#';
		c[M - 1] = '*';

		int mx = 0;
		int id = 0;
		int[] p = new int[M];
		for (int i = 1; i < M - 1; ++i) {
			if (mx > i) {
				p[i] = Math.min(p[2 * id - i], mx - i);
			}

			while (c[i + p[i]] == c[i - p[i]]) {
				++p[i];
			}
			if (i + p[i] > mx) {
				mx = i + p[i];
				id = i;
			}
		}

		int max = 0;
		int mid = 0;
		for (int i = 1; i < M - 1; ++i) {
			if (p[i] > max) {
				max = p[i];
				mid = i;
			}
		}

		return new String(c).substring(mid - p[mid] + 2, mid + p[mid] - 1)
				.replaceAll("#", "");
	}
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值