题解 | #最长回文子串#

最长回文子串

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

import java.util.*;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        while (in.hasNext()) { // 注意 while 处理多个 case
            String s = in.next();
            int length = s.length();
            int maxLength = 0;
            for (int i = 0; i < length; i++) {
                for (int j = length; j > i; j--) {
                    //长度达标、首位相同,再判断是否为回文子串
                    if (j - i > maxLength && s.charAt(j - 1) == s.charAt(i)) {
                        String temp = s.substring(i, j);
                        //是回文子串
                        if (check(temp)) {
                            //更新结果
                            maxLength = temp.length();
                        }
                    }
                }
            }
            System.out.println(maxLength);
        }
    }
    public static boolean check(String s) {
        StringBuilder sb = new StringBuilder(s);
        return s.equals(sb.reverse().toString());
    }
}

全部评论

相关推荐

饼子吃到撑:当我看到外企的时候,我就知道这大概率可能是真的
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务