最长 回文子串

本文探讨了如何在给定字符串中找到最长的回文子串,并提供了算法实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

n^2的方法

package String;

/**
 * @Title: Longest_Palindromic_Substring.java
 * @Package String
 * @Description: TODO
 * @author nutc
 * @date 2013-8-27 下午8:31:39
 * @version V1.0
 */
public class Longest_Palindromic_Substring {

	public static void main(String args[]) {
		Longest_Palindromic_Substring l = new Longest_Palindromic_Substring();
		String s = "abb";
		System.out.println(l.longestPalindrome(s));
	}

	public String longestPalindrome(String s) {

		if (s == null || s.length() <= 1)
			return s; // String 的长度有括号!
		int longest = 0;
		int index = 0;
		char[] c = s.toCharArray();
		for (int i = 1; i < c.length; i++) {

			int now = getLong(c, i - 1, i + 1) + 1;
			if (c[i] == c[i - 1])
				now = Math.max(now, getLong(c, i - 2, i + 1)+2);
			if (now > longest) {
				longest = now;
				index = i - now / 2;
			}
		}
		return s.substring(index,index+ longest); // substring 小写啊 白痴,是index+ longest而不是longest  !!!!
	}

	public int getLong(char[] s, int i, int j) {
		int count = 0;
		while (i >= 0 && j < s.length && s[i] == s[j]) {
			i--;
			j++;
			count++;
		}
		return count * 2;
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值