题解 | 最长回文子串

最长回文子串

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

import java.util.Scanner;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String str = in.nextLine();
        int maxLength = 0;
        for (int i = 0; i < str.length(); i++) {
            for (int j = i + 1; j <= str.length() / 2; j++) {
                if (j - i < (double)maxLength / 2) {
                    continue;
                }
                String left = str.substring(i, j);
                String right = str.substring(j, j + (j - i));
                StringBuilder sb = new StringBuilder(right).reverse();
                if (left.equals(sb.toString())) {
                    maxLength = (j - i) * 2;
                } else {
                    if (j - 1 > i) {
                        right = str.substring(j - 1, j - 1 + (j - i));
                        sb = new StringBuilder(right).reverse();
                        if (left.equals(sb.toString())) {
                            maxLength = (j - i - 1) * 2 + 1;
                        }
                    }
                }
            }
        }
        System.out.println(maxLength);
    }
}

全部评论

相关推荐

我也不知道起什么名字...:我感觉刷到8-10遍就悟了,之前特别难懂的题,现在就很自然的感觉不就这样的吗。比如链表排序,两个有序数组求中位数,背包问题等
牛客激励计划
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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