题解 | #HJ085 最长回文子串#

最长回文子串

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

import java.util.Scanner;

/**
 * HJ85 最长回文子串 - 简单
 */
public class HJ085 {

    public static void main(String args[]) {
        Scanner sc = new Scanner(System.in);
        while (sc.hasNext()) {
            String str = sc.nextLine();
            int max = getMaxPalindromeStr2(str);
            System.out.print(max);
        }
        sc.close();
    }

    private static int getMaxPalindromeStr2(String str) {
        // 双指针遍历找到最长子串
        for (int i = 0; i < str.length(); i++) {
            for (int j = 0; j < i + 1; j++) {
                String toBeJuged = str.substring(j, str.length() - i + j);
                if (isPalindromeStr(toBeJuged)) {
                    return toBeJuged.length();
                }
            }
        }
        return 0;
    }

    // 判断一个字符串是否是回文字符串的方法
    public static boolean isPalindromeStr(String s) {
        return s.equals(new StringBuilder(s).reverse().toString());
    }
}
全部评论
Math.max(max,j-i);这一步为什么不能换成max = oBeJuged.length();因为是从两头开始找的,第一次碰到的应该就是最长的回文串了吧。
点赞 回复 分享
发布于 2022-05-05 17:53

相关推荐

评论
5
8
分享

创作者周榜

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