题解 | #最长回文子串#

最长回文子串

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

import java.lang.Math;
import java.util.Scanner;

// 注意类名必须为 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
            char[] str = in.nextLine().toCharArray();
            int pdLength = Integer.MIN_VALUE;
            for (int i = 0; i < str.length - 1; ++i) {
                int l = 1;
                if (str[i] == str[i + 1]) {
                    l = 2;
                    int left = i - 1, right = i + 2;
                    while (left >= 0 && right < str.length) {
                        if (str[left--] == str[right++]) {
                            l += 2;
                        } else break;
                    }
                    pdLength = Math.max(l, pdLength);
                }
                if (i > 0 && str[i - 1] == str[i + 1]) {
                    l = 3;
                    int left = i - 2, right = i + 2;
                    while (left >= 0 && right < str.length) {
                        if (str[left--] == str[right++]) {
                            l += 2;
                        } else break;
                    }
                    pdLength = Math.max(l, pdLength);
                }
            }
            System.out.println(pdLength);
        }
    }
}

全部评论

相关推荐

09-28 01:10
中山大学 运营
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

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