/**
* @program: zcy
* @description:中心拓展算法
* @author: ZCY
* @create: 2022-06-22 10:01
**/
public class Main3 {
public static void main(String[] args) {
String str = "abaabc";
int lenMax = 1;
int begin=0;
//从0开始为了保证“bb”这种情况
for (int i = 0; i < str.length(); i++) {
int curMax = Math.max(maxLengthStr(str, i, i), maxLengthStr(str, i, i + 1));
if (curMax > lenMax) {
lenMax = curMax;
//最长子串的头位置下标
begin = i-(curMax-1)/2;
}
}
System.out.println("-------------------------------------");
System.out.println(lenMax);
System.out.println(str.substring(begin,begin+lenMax));
System.out.println("-------------------------------------");
}
public static int maxLengthStr(String str, int i, int j) {
while (i => 0 && j < str.length() && str.charAt(i) == str.charAt(j)) {
i--;
j++;
}
return j - i - 1;
}
}
Java求最长回文子串
于 2022-06-23 17:25:27 首次发布