题解 | #密码截取#
密码截取
https://www.nowcoder.com/practice/3cd4621963e8454594f00199f4536bb1
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String in = sc.nextLine();
String[] str = in.split("");
System.out.println(longestPwd(str));
}
public static int longestPwd(String[] str) {
int maxLong = 1;
int n = str.length;
int[] nums = new int[n];
nums[0] = 1;
for (int i = 1; i < n - 1; i++) {
//跳过相同的字符
if (str[i].equals(str[i - 1])) {
nums[i] = nums[i - 1];
continue;
}
nums[i] = 1;
int left = i - 1;
int right = i + 1;
//找到左边第一个不同的字符
while (left > 0 && str[left].equals(str[i])) {
left--;
nums[i]++;
}
//找到右边第一个不同的字符
while (right < n && str[right].equals(str[i])) {
right++;
nums[i]++;
}
for (int j = 0; right + j < n && left - j >= 0; j++) {
if (str[left - j].equals(str[right + j])) {
nums[i] += 2;
} else {
break;
}
}
}
for (int i = 0; i < n; i++) {
maxLong = Math.max(maxLong, nums[i]);
}
return maxLong;
}
}
