最长 回文子串

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;
	}
}


你可能感兴趣的:(最长 回文子串)