题解 | #最长回文子串#
最长回文子串
http://www.nowcoder.com/practice/12e081cd10ee4794a2bd70c7d68f5507
import java.util.*;
public class Main{
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String str = in.nextLine();
//len:每次外层循环截取的子串固定长度(以该固定长度移动),从最大开始递减
for(int len = str.length(); len >=1; len-- ){
//以固定长度滑动截取
for(int i = 0; i+len <= str.length(); i++){
String subStr = str.substring(i, i+len);
if(isSpecialStr(subStr)){
System.out.println(subStr.length());
return;
}
}
}
}
//判断是否是回文串,即前后对称
private static boolean isSpecialStr(String subStr) {
char[] chars = subStr.toCharArray();
for(int i = 0, j = chars.length-1; i < chars.length / 2; i++, j--){
if(chars[i] != chars[j]){
return false;
}
}
return true;
}
}