题解 | #最长回文子串#

最长回文子串

https://www.nowcoder.com/practice/12e081cd10ee4794a2bd70c7d68f5507

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();
            int maxLength = 0;// 最长回文子串的长度
            String child = "";// 子串
            String[] split = str.split("");
            for (int i = 0; i < split.length; i++) {
                for (int j = i+1; j <= split.length; j++) {
                    // 遍历所有子串
                    child = str.substring(i, j);
                    // 子串是回文子串,且比现有回文子串长度大,则更新最大值
                    if(checkChild(child) && maxLength < child.length()){
                        maxLength = child.length();
                    }
                }
            }
            System.out.println(maxLength);
        }
    }

    // 校验字符串是否是回文子串
    public static boolean checkChild(String child) {
        for(int k = 0;k<child.length()/2;k++){
            // 判断是否对称
            if(!(child.charAt(k) == child.charAt(child.length()-1-k))){
                return false;
            }
        }
        return true;
    }

}

全部评论

相关推荐

昨天 11:27
门头沟学院 Java
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
06-21 11:29
凉风落木楚山秋:他们两都收获了流量,只有爷浪费了时间
点赞 评论 收藏
分享
昨天 13:44
门头沟学院 Java
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务