下面这种写法结果虽然正确,但是字符串太长时,计算太耗时,不符合题目要求。
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (sc.hasNext()) {
String str = sc.nextLine();
int max = 0;
int length = str.length();
for (int i = 0; i < length; i++) {
for (int j = length; j > i; j--) {
if (isSymmetry(str, i, j)) {
max = Math.max(max, j - i);
}
}
}
System.out.println(max);
}
sc.close();
}
private static boolean isSymmetry(String str, int i, int j) {
String sub = str.substring(i, j);
StringBuilder sb = new StringBuilder(sub);
return sb.reverse().toString().equals(sub);
}
}
最优写法:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String s = sc.nextLine();
System.out.println(solution(s));
}
private static int solution(String s) {
int res = 0;
for(int i = 0; i < s.length(); i++) {
// ABA型
int len1 = longest(s, i, i);
// ABBA型
int len2 = longest(s, i, i + 1);
res = Math.max(res, len1 > len2 ? len1 : len2);
}
return res;
}
private static int longest(String s, int l, int r) {
while(l >= 0 && r < s.length() && s.charAt(l) == s.charAt(r)) {
l--;
r++;
}
return r - l - 1;
}
}