描述
给定一个仅包含小写字母的字符串,求它的最长回文子串的长度。
所谓回文串,指左右对称的字符串。
所谓子串,指一个字符串删掉其部分前缀和后缀(也可以不删)的字符串
数据范围:字符串长度1\le s\le 350\1≤s≤350
进阶:时间复杂度:O(n)\O(n) ,空间复杂度:O(n)\O(n)
输入描述:
输入一个仅包含小写字母的字符串
输出描述:
返回最长回文子串的长度
示例1
输入:
cdabbacc复制输出:
4复制说明:
abba为最长的回文子串
package org.example;
import java.util.Scanner;
public class Hj54 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (scanner.hasNext()){
String s = scanner.nextLine();
int max = 0;
for (int i = 0; i < s.length(); i++) {
for (int length = s.length(); length > i; length--) {
String str = s.substring(i, length);
if(checkpali(str)){
max = Math.max(max, length-i);
}
}
}
System.out.println(max);
}
}
public static boolean checkpali(String s){
return s.equals(new StringBuilder(s).reverse().toString());
}
}