题解 | #最长回文子串#
最长回文子串
https://www.nowcoder.com/practice/12e081cd10ee4794a2bd70c7d68f5507
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String str = in.next();
int count = 2;//最长回文串>=2
//外循环控制s1第一个数的下标
for (int i = 0; i < str.length() - 1; i++) {
//然后内循环s1的值末尾从i+1一直到最后
for (int j = i + 1; j < str.length(); j++) {
String s1 = str.substring(i, j+1);
if (ishuiwen(s1)) {
count = Math.max(s1.length(), count);
}
}
}
System.out.print(count);
}
//判断这整个字符串是否回文
private static boolean ishuiwen(String str) {
int len = str.length();
for (int i = 0; i < len / 2; i++) {
if (str.charAt(i) != str.charAt(len - 1 - i)) {
return false;
}
}
return true;
}
}
单纯判断一个字符串是否回文还是简单,从头到尾比到中间就行了,ishuiwen()
主要是怎么判断要取哪断字符串,我这就穷举了,智商只到这里
