题解 | #密码截取#
密码截取
http://www.nowcoder.com/practice/3cd4621963e8454594f00199f4536bb1
内存和时间都是85以上,还可以继续优化。
import java.util.*; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); while (sc.hasNext()) { String str = sc.next(); if (str.length() == 1) { System.out.println(1); return; } int ama = Math.max(maxLength1(str), maxLength2(str)); System.out.println(ama); } } private static int maxLength2(String str) { int max = 0; for (int a = 0; a < str.length(); a++) { if (a > str.length() - 2) { break; } if (str.charAt(a) != str.charAt(a + 1)) { continue; } int maxCount = 2; // 本次找到得最长长度 int bMax = Math.max(str.length() - a, a); for (int b = 1; b < bMax; b++) { if (a + b + 1 >= str.length()) { break; } if (a - b < 0) { break; } if (str.charAt(a - b) == str.charAt(a + b + 1)) { maxCount += 2; if (max < maxCount) { max = maxCount; } } else { break; } } } return max; } private static int maxLength1(String str) { int max = 0; for (int a = 1; a < str.length(); a++) { int maxCount = 1; //本次找到得最长长度 int bMax = Math.max(str.length() - a, a); for (int b = 1; b < bMax; b++) { if (a + b > str.length() - 1) { break; } if (a - b < 0) { break; } if (str.charAt(a - b) == str.charAt(a + b)) { maxCount += 2; if (max < maxCount) { max = maxCount; } } else { break; } } } return max; } }