题解 | #最长回文子串#
最长回文子串
http://www.nowcoder.com/practice/12e081cd10ee4794a2bd70c7d68f5507
import java.util.Scanner;
public class Main{
public static void main(String[] args){
//ccabbadc cdabbacc abcbaaa aaabcba
Scanner sc = new Scanner(System.in);
while(sc.hasNext()){
String str = sc.nextLine();
int max=0;
for(int i=0;i<str.length();i++){
for(int j=i+2;j<=str.length();j++){
String sub = str.substring(i,j);
int subLen= sub.length();
if(subLen>=2){
//temp表示字符串的前一半 如果字符串长度是奇数,则一半的前一位
String temp = sub.substring(0,subLen/2);
//temp是表示字符串的后一半,如果是奇数,中间位留着,是中间之后的后一半
StringBuilder temp2= new StringBuilder(sub.substring(subLen%2==0? (subLen/2) : (subLen/2+1)));
temp2.reverse();//反转 和temp做对比
if(temp.equals(temp2.toString())){
max=max>sub.length()?max:sub.length();
}
}
}
}
System.out.println(max);
}
}
}