算法1:暴力解法,枚举所有子串,对每个子串判断是否为回文,复杂度为O(n^3)
import java.util.Scanner;
/**
* 最长回文子串,暴力解决,找到字符串中的每一个子串,记录下来其中最长的
* @author buder_cp
*
*/
public class 最长回文子串暴力 {
public static boolean isPanlidrome(String s, int start, int end) {
for (int i = start, j = end; i < j; i++, j--) {
if (s.charAt(i) != s.charAt(j)) {
return false;
}
}
return true;
}
public static String longestPalidrome(String s) {
int n = s.length();
int max = 0;
int from = 0;
int to = 1;
for (int i = 0; i < n; i++) {
for (int j = i; j < n; j++) {
if (isPanlidrome(s, i, j)) {
if (j - i + 1 > max) {
max = j - i + 1;
from = i;
to = j;
}
}
}
}
return s.substring(from, to + 1);
}
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
System.out.println(longestPalidrome(sc.nextLine()));
}
}
算法2:以某个元素为中心,分别计算偶数长度的回文最大长度和奇数长度的回文最大长度。时间复杂度O(n^2),空间O(1)
public class 最长回文子串中心扩展 {
public static void main(String[] args){
String s = "12321";
int len = s.length();
int max = 1;
int start = 0;
for(int i = 1; i < len; i++){
int low = i-1; //偶数情况
int high = i;
while(low >= 0 && high < len && s.charAt(low)==s.charAt(high)){
low--;
high++;
}
if(high-low-1 > max){
max = high-low-1;
start = low+1;
}
low = i-1; //奇数情况
high = i+1;
while(low >= 0 && high < len && s.charAt(low)==s.charAt(high)){
low--;
high++;
}
if(high-low-1 > max){
max = high-low-1;
start = low+1;
}
}
System.out.println(max);
}
}