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.

Solution 1 O(n^2)

public class Solution {
    public String longestPalindrome(String s) {
		// Start typing your Java solution below
		// DO NOT write main() function
		int len = s.length();
		if(len == 0)
			return "";
		String longest = s.substring(0,1);
		for(int i = 0; i < len - 1; i++){
			String temp = expandAroundCenter(s, i, i);
			if(temp.length() > longest.length())
				longest = temp;
			temp = expandAroundCenter(s, i, i + 1);
			if(temp.length() > longest.length())
				longest = temp;
		}
		return longest;
	}
	public String expandAroundCenter(String s, int left, int right){
		int len = s.length();
		while(left >= 0 && right <= len - 1 && s.charAt(left) == s.charAt(right)){
			left--;
			right++;
		}
		return s.substring(left + 1, right);
	}
}


Solution 2 O(n) Manacher Algorithm

 I messed up i with i_mirror when writing this code, which took me two hours to find out the bug....

 

public class Solution {
    public String longestPalindrome(String s) {
		int len = s.length();
		StringBuilder sb = new StringBuilder("#");
		for (int i = 0; i < len; i++) {
			sb.append(s.charAt(i));
			sb.append("#");
		}
		String new_s = sb.toString();
		len = new_s.length();
		int[] P = new int[len];
		int max_radius = 1;
		int res_center = 1;
		int C = 1, R = 1;
		for (int i = 1; i < len - 1; i++) {
			int i_mirror = 2 * C - i;// i_mirror = C - (i - C)
			P[i] = (R > i) ? Math.min(R - i, P[i_mirror]) : 0;

			// expand paindrome centered at i if valid
			if ((i - 1 - P[i]) >= 0 && (i + 1 + P[i]) < len) {
				while (new_s.charAt(i + 1 + P[i]) == new_s.charAt(i - 1 - P[i])){
					P[i]++;
					if ((i - 1 - P[i]) < 0 || (i + 1 + P[i]) >= len)
						break;
				}
			}
			// if palindrome centered at i expand past R
			// adjust center based on expanded palindrome
			if (P[i] > max_radius) {
				max_radius = P[i];
				res_center = i;
			}
			if (i + P[i] > R) {
				C = i ;
				R = i + P[i];
			}
		}
		return s.substring((res_center - max_radius) / 2,
				(res_center + max_radius) / 2);
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值