题解 | #最长回文子串#
最长回文子串
http://www.nowcoder.com/practice/12e081cd10ee4794a2bd70c7d68f5507
import java.util.Scanner;
public class Main{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
while(sc.hasNextLine()){
String str = sc.nextLine();
System.out.println(getCount(str));
}
}
public static int getCount(String str1){
for(int j=0;j<=str1.length()-i;j++){
String str3 = str1.substring(j,j+i);
StringBuffer sb = new StringBuffer(str3);
max = str3.length();
}
}
}
return max;
}
}
public class Main{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
while(sc.hasNextLine()){
String str = sc.nextLine();
System.out.println(getCount(str));
}
}
public static int getCount(String str1){
int max = 0;
//首先遍历该字符串的所有子字符串,i表示子字符串的长度, j 表示从第几个位置开始取子字符串
for(int i=1;i<=str1.length();i++){for(int j=0;j<=str1.length()-i;j++){
String str3 = str1.substring(j,j+i);
StringBuffer sb = new StringBuffer(str3);
String str2 = sb.reverse().toString();
//回文子串是逆序和顺序一样,同时给他赋值一个当前的长度,循环把最长的回文子串找到
if(str2.equals(str3) && str3.length()>max){max = str3.length();
}
}
}
return max;
}
}