题解 | #密码截取#
密码截取
http://www.nowcoder.com/practice/3cd4621963e8454594f00199f4536bb1
import java.util.Scanner;
public class Main{ public static void main(String[] args){ Scanner sc = new Scanner(System.in); while(sc.hasNext()){ String str = sc.nextLine(); // 输出结果 System.out.println(solution(str)); } }
private static int solution(String str){
// 定义一个对象用于存储回文字符串的长度
int len = 0;
int maxLen = 0;
// 将字符串转换为字符数组
char[] chars = str.toCharArray();
for(int i = 0; i < chars.length; i++){
// aba型回文
len = longest(chars,i - 1,i + 1,1);
if(len != 1 && len > maxLen) maxLen = len;
// abba型回文
len = longest(chars,i,i + 1,0);
if(len > maxLen) maxLen = len;
}
return maxLen;
}
private static int longest(char[] c,int m, int n,int l){
if( m >= 0 && n < c.length && c[m] == c[n]){
l += 2;
return longest(c,m - 1, n + 1, l);
} else{
return l;
}
}
}