题解 | #最长回文子串#
最长回文子串
https://www.nowcoder.com/practice/12e081cd10ee4794a2bd70c7d68f5507
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String str = sc.nextLine();
int count = 1;
for (int i = 0; i < str.length(); i++) {
count=Math.max(count,getCount(str,count,i-1,i+1));
count=Math.max(count,getCount(str,count,i,i+1));
}
System.out.println(count);
}
public static int getCount(String str, int count, int left, int right) {
while (true) {
//懒狗用trycatch结构,报错就停止,不用想哪里越界惹
try {
if (str.charAt(left) == str.charAt(right)) {
count = Math.max(count, right - left+1);
left--;
right++;
} else {
break;
}
} catch (Exception e) {
break;
}
}
return count;
}
}
凡岛公司福利 667人发布