暴力枚举所有情况,找到最长字符串
import java.util.Scanner;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
// 注意 hasNext 和 hasNextLine 的区别
while (in.hasNext()) { // 注意 while 处理多个 case
String a = in.nextLine();
System.out.println(cathcerWork(a));
//System.out.println(isSuccess(a));
}
}
public static int cathcerWork(String a) {
int maxLen = 0;
for (int i = 0; i < a.length(); i++) {
for (int j = a.length(); j >= i; j--) {
String temp = a.substring(i, j);
int tempLent = temp.length();
if (tempLent < maxLen) {
break;
}
if (isSuccess(temp)) {
maxLen = tempLent;
break;
}
}
}
return maxLen;
}
public static boolean isSuccess(String a) {
int length = a.length();
for (int i = 0; i < length / 2 + 1; i++) {
if (a.charAt(i) != a.charAt(length- i - 1)) {
return false;
}
}
return true;
}
}